import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
import { MatStepper } from '@angular/material/stepper';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { configuration } from '../website/entities/configuration';
import { ConfigurationService } from '../website/shared/services/configuration.service';


@Component({
  selector: 'app-configuration',
  templateUrl: './configuration.component.html',
  styleUrls: ['./configuration.component.scss']
})
export class ConfigurationComponent implements OnInit {

  public configurationForm: FormGroup;
  public setUpForm: FormGroup;
  public configuration: configuration = new configuration();
  public versions = ['1.1'];
  public databases: any;
  public isetupDatabaseConfiguration: boolean = false;
  public isInstallMasterData: boolean = false;
  public isInstallSampleData: boolean = false;
  public databaseState: string = 'Creating';
  public masterDataState: string = 'Creating';
  public sampleDataState: string = 'Creating';
  public isTested: boolean = false;
  public isBackupDatabased: boolean = false;
  public show: boolean = false;
  public error!: string;
  public userName: string = 'admin@demo.com';
  public password: string = 'Demo@1234';
  public isFullSetup: boolean = false;
  public connectionError: boolean = false;
  public credential!: any;

  // steps = ['Step 1', 'Step 2', 'Step 3'];
  // @ViewChild('stepper') stepper: MatStepper;
  public selectedIndex: number = 0;

  constructor(
    private configurationService: ConfigurationService,
    private router: Router,
    private formBuilder: FormBuilder,
    private toastrService: ToastrService
  ) {
    const link1 = document.createElement('link');
    link1.rel = 'stylesheet';
    link1.href = 'assets/admin/scss/bootstrap4.css';
    document.head.insertBefore(link1, document.head.firstChild);
    this.configurationForm = formBuilder.group({
      'MYSQL_HOST': [null, [Validators.required]],
      'MYSQL_USER': [null, [Validators.required]],
      'MYSQL_PASSWORD': [null, [Validators.required]],
      'MYSQL_PORT': [null, [Validators.required]],
    });
    this.setUpForm = formBuilder.group({
      'MYSQL_DATABASE': ['creditapp'],
      'username': ['creditapp_admin'],
      'password': [null],
      'previousVersionInstalled': [true],
      'version': [null],
      'database': [null],
      'isCreateDatabaseUser': [null],
      'isInstallMasterData': [null],
      'isInstallSampleData': [null]
    });

  }

  ngOnInit(): void {
    const link2 = document.createElement('link');
    link2.rel = 'stylesheet';
    link2.href = 'assets/admin/scss/indigo-pink.css';
    document.head.insertBefore(link2, document.head.firstChild);
    let jsonData = JSON.parse(sessionStorage.getItem("jsonData") ?? 'null');
    this.credential = "UserName:" + this.userName + "\n" + "Password:" + this.password;
    if (jsonData) {
      this.configurationForm.get('MYSQL_HOST')!.setValue(jsonData.MYSQL_HOST != '<MYSQL_HOST>' ? jsonData.MYSQL_HOST : null);
      this.configurationForm.get('MYSQL_USER')!.setValue(jsonData.MYSQL_USER != '<MYSQL_USER>' ? jsonData.MYSQL_USER : null);
      this.configurationForm.get('MYSQL_PASSWORD')!.setValue(jsonData.MYSQL_PASSWORD != '<MYSQL_PASSWORD>' ? jsonData.MYSQL_PASSWORD : null);
      this.configurationForm.get('MYSQL_PORT')!.setValue(jsonData.MYSQL_PORT != '<MYSQL_PORT>' ? jsonData.MYSQL_PASSWORD : null);
      // this.configurationForm.get('MYSQL_HOST').setValue(jsonData.MYSQL_HOST != '<MYSQL_HOST>' ? jsonData.MYSQL_HOST : null);
      // if (jsonData.MYSQL_HOST == '<MYSQL_HOST>')
      //   this.selectedIndex = 0;
      // else if (jsonData.MYSQL_DATABASE == '<MYSQL_DATABASE>')
      //   this.selectedIndex = 1;
      // if (jsonData.MYSQL_HOST != '<MSQL_HOST>') {
      //   this.configurationForm
      // }
    }

    // if (activeStep) {
    //   this.stepper.selectedIndex = index;
    // }
    this.setUpForm.get('previousVersionInstalled')?.setValue("false");
  }

  // stepChange(event) {
  //   this.selectedIndex = event.selectedIndex;
  // }

  public async testConnection(form: any) {
    try {
      if (form.valid) {
        this.configuration = this.configurationForm.value;
        let res = await this.configurationService.testConnection(this.configuration);
        if (res && res.status == 200) {
          this.databases = res.recordList;
          this.isTested = true;
          this.selectedIndex = 1;
        }
        else {

        }
      }
      else {
        Object.keys(form.controls).forEach(key => {
          form.controls[key].markAsTouched();
        });
      }
    } catch (error) {
      this.isTested = true;
      this.connectionError = true;
      console.log(error);

    }
  }

  public async databaseConfiguration(form: any) {
    try {
      debugger
      if (form.valid) {
        this.selectedIndex = 2;
        this.databaseState = 'Creating';
        this.masterDataState = 'Creating';
        this.sampleDataState = 'Creating';
        let configuration = this.setUpForm.value;
        if (configuration.previousVersionInstalled == 'true') {
          configuration.MYSQL_DATABASE = configuration.database;
          // configuration.version = 
        }
        this.databaseState = 'Creating';
        let res = await this.configurationService.databaseConfiguration(configuration);
        if (res && res.status == 200) {
          this.databaseState = 'created';
          this.isetupDatabaseConfiguration = true;
          if (res.recordList && res.recordList.length > 0) {
            this.userName = res.recordList[0].email;
            this.password = 'admin';

          }
          if (configuration.isInstallMasterData) {

            let res = await this.configurationService.installMasterData(configuration);
            if (res && res.status == 200) {
              this.isInstallMasterData = true;
              this.masterDataState = 'created';
              if (configuration.isInstallSampleData) {
                let res = await this.configurationService.installSampleData();
                if (res && res.status == 200) {
                  this.sampleDataState = 'created';
                  this.isInstallSampleData = true;
                }
                else {
                  this.isInstallSampleData = false;
                  this.sampleDataState = 'Error';
                }
              }
            }
          }
          else {
            this.isInstallMasterData = false;
            this.masterDataState = 'Error';
          }
        }
        else {
          this.isetupDatabaseConfiguration = false;
          this.databaseState = 'Error';
        }
        this.isFullSetup = true;
      }

      else {
        Object.keys(form.controls).forEach(key => {
          form.controls[key].markAsTouched();
        });
      }
    } catch (error: any) {
      if (this.databaseState != 'created')
        this.databaseState = 'Error';
      this.masterDataState = 'Error';
      this.sampleDataState = 'Error';
      this.isTested = false;
      this.error = error?.error?.message;
    }
  }

  public checkPreviousVersionInstalled() {
    let isVersionInstalled = this.setUpForm.get('previousVersionInstalled')!.value;
    // if (isVersionInstalled == 'true') {
    //   this.setUpForm.get('version').addValidators([Validators.required])
    // }
    // else {
    this.setUpForm.get('version')!.setValue(null);
    // }
  }

  public async backupDatabase() {
    try {
      let configuration = this.configurationForm.value;
      configuration.MYSQL_DATABASE = this.setUpForm.get('database')!.value;
      let res = await this.configurationService.backupDatabase(configuration);
      if (res && res.status == 200) {
        this.isBackupDatabased = true;
      }
    } catch (error) {
      console.log(error);
    }
  }

  showPassword() {
    this.show = !this.show;
  }

  public copiedError() {
    this.toastrService.success("Copied Error Successfully");

  }

  public generateRandomPassword() {
    const length = 8;
    const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let password = "";
    for (let i = 0; i < length; i++) {
      const randomIndex = Math.floor(Math.random() * charset.length);
      password += charset[randomIndex];
    }
    this.setUpForm.get('password')!.setValue(password);
  }

  public gotoLogin() {
    this.router.navigate(['admin/login']);
    let data = JSON.stringify({
      "userName": this.userName,
      "password": this.password
    })
    sessionStorage.setItem('userDetail', data);
  }

  public reset() {
    this.connectionError = false;
    this.isTested = false
  }

  public copiedCredentail() {

    this.toastrService.success("Copied Successfully")
  }
}
