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 { 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';


@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 = 'Link to Xero';
	xeroAccCod: string = '';
	saveAccOk: boolean = false;
	
	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 = '';

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

			if (data.payconf) {
				this.settingsForm.get('vKey')!.enable();
			}
			this.owner = data;
			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.linkMsg = 'Link to Xero';
	      this.pmtServiceURL + '';
	      if ( this.linked2Xero ) {
	      	this.linkMsg = '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("Xero Payment confirmation disabled!!","Close",'warning');
		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.owner.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("ZGo URL copied to Clipboard!!","Close",'success');

		} catch (err) {
//			console.error("Error", err);  
			this.notifierService
			    .showNotification("Functionality not available for your browser. Use send button instead.","Close",'error');
		}
	}

	copyWooOwner(){
		try {
			navigator.clipboard.writeText(this.wooOwner);
			this.notifierService.showNotification("Owner ID copied to clipboard", "Close", "success");
		} catch (err) {
			this.notifierService.showNotification("Copying not available in your browser", "Close", "error");
		}
	}

	copyWooToken(){
		try {
			navigator.clipboard.writeText(this.wooToken);
			this.notifierService.showNotification("WooCommerce Token copied to clipboard", "Close", "success");
		} catch (err) {
			this.notifierService.showNotification("Copying not available in your browser", "Close", "error");
		}
	}

	generateWooToken(){
		this.wooService.createWooToken(this.owner._id!).subscribe(responseData => {
			if (responseData.status == 202) {
				this.notifierService.showNotification("WooCommerce Token generated!", "Close", "success");
				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("WooCommerce Token generation failed.", "Close", "error");
			}
		});
	}

	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(responseData => {
		   	  if (responseData.status == 202) {
			  	console.log('Account saved');
				this.notifierService
	 		        .showNotification("Account Code saved!!","Close",'success');
			  } else {
			  	console.log('Account not saved -> status[' + responseData.status + ']');
				this.notifierService
	 		        .showNotification("Account Code not saved","Close",'error');
			  }

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

	  } else {
			this.notifierService
			    .showNotification("Invalid Account code (10 chars max.)","Close",'error');
	  };
	}
/*
	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 );
   }
}
