import { Inject, Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatSlideToggleChange } from '@angular/material/slide-toggle';
import { UntypedFormBuilder, Validators, UntypedFormGroup, FormControl } from '@angular/forms';
import { Subject, Observable } from 'rxjs';
import { Owner } from '../owner.model';
import { XeroService } from '../xero.service';
import { WoocommerceService } from '../woocommerce.service';

import { NotifierService } from '../notifier.service';
import { faCopy } from '@fortawesome/free-solid-svg-icons';

import { LanguageService } from '../language.service';
import { LanguageData } from '../language.model';

@Component({
	selector: 'app-settings',
	templateUrl: './settings.component.html',
	styleUrls: ['/settings.component.css']
})

export class SettingsComponent implements OnInit {

 	// ------------------------------------
	//
	faCopy = faCopy;
 	// ------------------------------------
	settingsForm: UntypedFormGroup;
	accCodForm:	UntypedFormGroup;
	owner: Owner;
	useZats: boolean;
	proVersion: boolean = false;
	useVKey: boolean = false;
	linkMsg: string = '';
	xeroAccCod: string = '';
	saveAccOk: boolean = false;
	private viewkey: string = '';
	
	coins = [
		{
			label: 'US Dollar',
			symbol: 'usd'
		},{
			label: 'Euro',
			symbol: 'eur'
		},{
			label: 'British Pound',
			symbol: 'gbp'
		},{
			label: 'Canadian Dollar',
			symbol: 'cad'
		},{
			label: 'Australian Dollar',
			symbol: 'aud'
		},{
			label: 'New Zealand Dollar',
			symbol: 'nzd'
		}
	];
	xeroLink: string = '';
	localToken: string = '';
	clientId: string = '';
	wooOwner: string = '';
	wooToken: string = '';
	wooUrl: string = '';
	wooOwnerUpdate: Observable<string>;
	wooTokenUpdate: Observable<string>;
	wooUrlUpdate: Observable<string>;

	clientIdUpdate: Observable<string>;
	accCodeUpdate: Observable<string>;
	linked2Xero : boolean = false;
	pmtServiceURL : string = '';
	// -------------------------------------
    //
    // Language Support
    //
    vE = {
		settingsAcodeInvalid : '',
		settingsAcodeLbl : '',
		settingsAcodeNotsaved : '',
		settingsAcodeSaved : '',
		settingsCloseBtn : '', 
		settingsConfirmPayments : '',
		settingsCopyNotavail : '',
		settingsCurrencyLbl : '',
		settingsLink2Xero : '',
		settingsNameLbl : '',
		settingsNamePlaceholder : '',
		settingsNotservClose : '',
		settingsNotservError : '',
		settingsNotservSuccess : '',
		settingsNotservWarning : '',
		settingsOwneridCopied : '',
		settingsOwneridNotcopied : '',
		settingsPmtservURL : '',
		settingsRelink2Xero : '',
		settingsSaveBtn : '',
		settingsTabIntegrations : '',
		settingsTabMainlbl : '',
		settingsURLCopied : '',
		settingsUseSatoshi : '',
		settingsViewTitle : '',
		settingsVkeyLbl : '',
		settingsVkeyPlaceholder : '',
		settingsWCClosebtn : '',
		settingsWCGentoken : '',
		settingsWCLbl : '',
		settingsWCOwnerlbl : '',
		settingsWCTokenCopied : '',
		settingsWCTokenGenerated : '',
		settingsWCTokenGenfail : '',
		settingsWCTokenNotcopied : '',
		settingsXeroClosebtn : '', 
		settingsXeroLbl : '',
		settingsXeropmtConfirmdis : '',
		settingsXeroSavebtn : ''
    };
    //
    languageRdy = new Subject<boolean>();

    // ------------------------------------------------------------
	constructor(
		private languageService : LanguageService,
		private notifierService : NotifierService,
		private fb: UntypedFormBuilder,
		public xeroService: XeroService,
		public wooService: WoocommerceService,
		private dialogRef: MatDialogRef<SettingsComponent>,
		@Inject(MAT_DIALOG_DATA) public data: {o: Owner, v: string}) {
			this.useZats = data.o.zats;
			this.useVKey = data.o.payconf;
			this.settingsForm = fb.group({
					name: [data.o.name, Validators.required],
					currency: [data.o.currency, Validators.required],
					useZats: [data.o.zats,  Validators.required],
					useVKey: [data.o.payconf, Validators.required],
	//				proVersion: [data.invoices, Validators.required],
					vKey: [data.v]
				});
			this.accCodForm = fb.group ({
					xAcc: [this.xeroAccCod]
				});

			if (data.o.payconf) {
				this.settingsForm.get('vKey')!.enable();
			}
			this.owner = data.o;
			this.viewkey = data.v;
			this.proVersion = this.owner.invoices;
			if ( this.owner.crmToken !== '' ) {
			  this.linked2Xero = true;	
			}
			this.clientIdUpdate = xeroService.clientIdUpdate;
			xeroService.getXeroConfig();
			this.clientIdUpdate.subscribe(clientId => {
				this.clientId = clientId;
				this.xeroLink = `https://login.xero.com/identity/connect/authorize?response_type=code&client_id=${this.clientId}&redirect_uri=http%3A%2F%2Flocalhost%3A4200%2Fxeroauth&scope=accounting.transactions offline_access&state=${this.owner.address.substring(0, 6)}`
			});
			this.accCodeUpdate = xeroService.accCodeUpdate;
			xeroService.getXeroAccountCode(this.owner.address);
			this.accCodeUpdate.subscribe(accData => {
				this.xeroAccCod = accData;
				//console.log("xeroAccCod -> [" + this.xeroAccCod + "]");
				this.accCodForm.get('xAcc')!.setValue(this.xeroAccCod);
			});
			this.wooOwnerUpdate = wooService.ownerUpdate;
			this.wooTokenUpdate = wooService.tokenUpdate;
			this.wooUrlUpdate = wooService.siteurlUpdate;
			wooService.getWooToken(this.owner._id!);
			this.wooOwnerUpdate.subscribe(owData => {
				this.wooOwner = owData;
			});
			this.wooTokenUpdate.subscribe(tkData => {
				this.wooToken = tkData;
			});
			this.wooUrlUpdate.subscribe(uData => {
				this.wooUrl = uData;
			});
	}


	ngOnInit() {

	      this.settingsForm.get('vKey')!.disable();
  			// 
  			this.chgUILanguage();
         //console.log('SETTINGS: Return from chgUILanguage()');
         //
         this.languageRdy.subscribe (
         	  data => {
			      	this.linkMsg = this.vE.settingsLink2Xero; 
			      	this.pmtServiceURL + '';
			      	if ( this.linked2Xero ) {
		   	   		this.linkMsg = this.vE.settingsRelink2Xero; //'Relink to Xero';
		      			this.pmtServiceURL = 
		      				'https://zgo.cash/pmtservice?owner=' + 
		      	         this.owner._id + 
		      	         '&invoiceNo=[INVOICENUMBER]&currency=[CURRENCY]&amount=[AMOUNTDUE]&shortCode=[SHORTCODE]';
	      			}
         	  });
	}

	safeURL(s: string){
		return s.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
	}

	close() {

		this.dialogRef.close();
	}

	closeIntegration() {
		if ( (this.xeroAccCod == '') && (this.linked2Xero) ) 
			this.notifierService
		    .showNotification(this.vE.settingsXeropmtConfirmdis ,
		    	                this.vE.settingsNotservClose,'warning',
		    	                this.vE.settingsNotservWarning);
		this.dialogRef.close();
	}

	save() {
		this.owner.name = this.settingsForm.value.name;
		this.owner.currency = this.settingsForm.value.currency;
		this.owner.zats = this.settingsForm.value.useZats;
		this.owner.payconf = this.settingsForm.value.useVKey;
		this.viewkey = this.settingsForm.value.vKey;
		//this.owner.invoices = this.settingsForm.value.proVersion
		this.dialogRef.close(this.owner);
	}

	onChange(ob: MatSlideToggleChange) {
		this.useZats = ob.checked;
	}

	onChangeProVersion(ob: MatSlideToggleChange) {
		this.proVersion = ob.checked;
	}

	onChangeVKeyOn(ob: MatSlideToggleChange) {
//		console.log("Viewing key switch is " + 
//			        ( ob.checked ? "[ON]." : "[OFF]." ) );
        
        this.useVKey = ob.checked;

	    if ( ob.checked ) 
	      this.settingsForm.get('vKey')!.enable();
	    else 
	      this.settingsForm.get('vKey')!.disable();

	}

	copyUrl() {
//		console.log("Inside copyUrl()");
		if (navigator.clipboard) {
		};
		try {
			navigator.clipboard.writeText(this.pmtServiceURL);
			this.notifierService
			    .showNotification(this.vE.settingsURLCopied, 
			     	this.vE.settingsNotservClose,
			    	'success',
			    	this.vE.settingsNotservSuccess);

		} catch (err) {
//			console.error("Error", err);  
			this.notifierService
			    .showNotification(this.vE.settingsCopyNotavail,
			     	this.vE.settingsNotservClose,
			    	'error',
			    	this.vE.settingsNotservError);
		}
	}

	copyWooOwner(){
		try {
			navigator.clipboard.writeText(this.wooOwner);
			this.notifierService.showNotification(this.vE.settingsOwneridCopied, 
				this.vE.settingsNotservClose,
				"success",
				this.vE.settingsNotservSuccess);
		} catch (err) {
			this.notifierService.showNotification(this.vE.settingsOwneridNotcopied,
				this.vE.settingsNotservClose,
			   "error",
				this.vE.settingsNotservError);
		}
	}

	copyWooToken(){
		try {
			navigator.clipboard.writeText(this.wooToken);
			this.notifierService.showNotification(this.vE.settingsWCTokenCopied, 				
				this.vE.settingsNotservClose,
				"success",
				this.vE.settingsNotservSuccess);
		} catch (err) {
			this.notifierService.showNotification(this.vE.settingsWCTokenNotcopied,  				
				this.vE.settingsNotservClose,
			   "error",
				this.vE.settingsNotservError);
		}
	}

	generateWooToken(){
		this.wooService.createWooToken(this.owner._id!).subscribe(responseData => {
			if (responseData.status == 202) {
				this.notifierService.showNotification(
					this.vE.settingsWCTokenGenerated, 
					this.vE.settingsNotservClose,
					"success",
					this.vE.settingsNotservSuccess);
				this.wooService.getWooToken(this.owner._id!);
				this.wooOwnerUpdate.subscribe(owData => {
					this.wooOwner = owData;
				});
				this.wooTokenUpdate.subscribe(tkData => {
					this.wooToken = tkData;
				});
				this.wooUrlUpdate.subscribe(uData => {
					this.wooUrl = uData;
				});
				close();
			} else {
				this.notifierService.showNotification(
					this.vE.settingsWCTokenGenfail, 
					this.vE.settingsNotservClose,
			   	"error",
					this.vE.settingsNotservError);
			}
		});
	}

	saveAccCod() {

	  this.xeroAccCod = 	this.accCodForm.value.xAcc;
	  //console.log(">>> " + this.xeroAccCod);	
	  if ( this.xeroAccCod.length <= 10 ) {
         const obs = this.xeroService
                        .setXeroAccountCode(this.owner.address,
         	        			            this.xeroAccCod);
											obs.subscribe({ next: responseData => {
												if (responseData.status == 202) {
													//console.log('Account saved');
													this.notifierService
													.showNotification(this.vE.settingsAcodeSaved,
																	  this.vE.settingsNotservClose,
																	  "success",
																	  this.vE.settingsNotservSuccess);
												} else {
													//console.log('Account not saved -> status[' + responseData.status + ']');
													this.notifierService
													.showNotification(
														this.vE.settingsAcodeNotsaved, 
														this.vE.settingsNotservClose,
														"error",
														this.vE.settingsNotservError);
												}

											},
											error: error => {
												//console.log('Error saving Account Code -> ' + error.msg)
											}});

	  } else {
			this.notifierService
			    .showNotification(
			    		this.vE.settingsAcodeInvalid,
			    		this.vE.settingsNotservClose,
					   "error",
						this.vE.settingsNotservError);
	  };
	}
/*
	xeroAccCodChanged( arg: any ) {
		console.log("Account Code changed: " + arg.target.value);
//		console.log(arg);
		this.saveAccOk = (arg.target.value != this.xeroAccCod );
	}
*/
	checkStatus( arg : any ) {
		//console.log('onChange - checkStatus');
		//console.log(arg.target.value);
		this.saveAccOk = (arg.target.value != this.xeroAccCod );
   }

	chgUILanguage(){
      //console.log('SETTINGS.chgUILanguage Called ');
		this.languageService.getViewElements('settings').subscribe({
			next: response => {
				//console.log('Received >> ', response );
				//console.log('Language Code : ', response.language);
				//console.log('Component Name : ',response.component);
				//console.log('Language data : ',response.data);

				this.vE.settingsViewTitle = response.data.settings_view_title;
				this.vE.settingsTabMainlbl = response.data.settings_tab_mainlbl;
				this.vE.settingsNameLbl = response.data.settings_name_lbl;
				this.vE.settingsCurrencyLbl = response.data.settings_currency_lbl;
				this.vE.settingsNamePlaceholder = response.data.settings_name_placeholder;
				this.vE.settingsUseSatoshi = response.data.settings_use_satoshi;
				this.vE.settingsVkeyLbl = response.data.settings_vkey_lbl;
				this.vE.settingsVkeyPlaceholder = response.data.settings_vkey_placeholder;
				this.vE.settingsConfirmPayments = response.data.settings_confirm_payments;
				this.vE.settingsCloseBtn = response.data.settings_close_btn; 
				this.vE.settingsSaveBtn = response.data.settings_save_btn;
				this.vE.settingsTabIntegrations = response.data.settings_tab_integrations;
				this.vE.settingsXeroLbl = response.data.settings_xero_lbl;
				this.vE.settingsLink2Xero = response.data.settings_link_2xero;
				this.vE.settingsRelink2Xero = response.data.settings_relink_2xero;
				this.vE.settingsXeropmtConfirmdis = response.data.settings_xeropmt_confirmdis;
				this.vE.settingsNotservClose = response.data.settings_notserv_close;
				this.vE.settingsNotservWarning = response.data.settings_notserv_warning;
				this.vE.settingsPmtservURL = response.data.settings_pmtserv_url;	
				this.vE.settingsAcodeLbl = response.data.settings_acode_lbl;	
				this.vE.settingsXeroClosebtn = response.data.settings_xero_closebtn;
				this.vE.settingsXeroSavebtn = response.data.settings_xero_savebtn;
				this.vE.settingsWCLbl = response.data.settings_wc_lbl;
				this.vE.settingsWCGentoken = response.data.settings_wc_gentoken;
				this.vE.settingsWCOwnerlbl	= response.data.settings_wc_ownerlbl;   
				this.vE.settingsWCClosebtn = response.data.settings_wc_closebtn;     
				this.vE.settingsURLCopied = response.data.settings_url_copied;
				this.vE.settingsNotservSuccess = response.data.settings_notserv_success;
				this.vE.settingsNotservError = response.data.settings_notserv_error;
				this.vE.settingsCopyNotavail = response.data.settings_copy_notavail;
				this.vE.settingsOwneridCopied = response.data.settings_ownerid_copied;
				this.vE.settingsOwneridNotcopied = response.data.settings_ownerid_notcopied;
				this.vE.settingsWCTokenCopied = response.data.settings_wctoken_copied;
				this.vE.settingsWCTokenNotcopied = response.data.settings_wctoken_notcopied;
				this.vE.settingsWCTokenGenerated = response.data.settings_wctoken_generated;
				this.vE.settingsWCTokenGenfail = response.data.settings_wctoken_genfail;
				this.vE.settingsAcodeSaved = response.data.settings_acode_saved;
				this.vE.settingsAcodeNotsaved = response.data.settings_acode_notsaved;
				this.vE.settingsAcodeInvalid = response.data.settings_acode_invalid;
				//
				this.languageRdy.next(true);
			},
			error: error  => { console.log('Error >> ',error); }
		});
	}
}
