import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { FileUploader } from 'ng2-file-upload';
import { AuthenticationService } from 'src/app/hmg-common/services/authentication/authentication.service';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { ItemForSaleService } from '../services/service.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
  step: any = 1;
  categories: any = [];
  direction: string;
  uploaded: any = [];
  public selectedFile: any;
  indexLastObj: any = 0;
  addAttachRequest: any = [];
  selectedCategory: any;
  filterAllowedType: any = [
    "image/jpeg",
    "image/png",
    "image/jpg",
  ];
  itemInfo: string;
  itemDescription: string;
  itemCondition: string;
  itemPrice: any;
  regions: any = [];
  regionID: any = 1;
  editItem: any;
  constructor(public ts: TranslatorService, private authService: AuthenticationService, private sanitizer: DomSanitizer, public cs: CommonService, private itemService: ItemForSaleService) { }

  ngOnInit() {
    this.direction = TranslatorService.getCurrentDirection();
    this.categories = this.cs.sharedService.getSharedData(ItemForSaleService.CATEGORIES, false);
    this.getRegion();
    this.editItem = this.cs.sharedService.getSharedData(ItemForSaleService.EDIT_ITEMS);
    if (this.editItem) {
      this.setEditPage();
    }
  }
  getRegion() {
    this.itemService.getRegion({}, () => { }, this.ts.trPK('general', 'retry')).subscribe((result) => {
      this.regions = this.itemService.parser(result);
      console.log(this.regions);
    })
  }
  openItem() {
    this.cs.navigateForward('/itemforsale/items');
  }
  nextStep(category) {
    this.selectedCategory = category;
    this.step = 2;
  }
  openMyAds() {
    this.cs.navigateForward('/itemforsale/my-ads');
  }

  onFileSelectedclick(event) {
    event.target.value = '';
  }
  public uploader: FileUploader = new FileUploader({
    allowedMimeType: [
      "image/jpeg",
      "image/png",
      "image/jpg",
    ],
    maxFileSize: 10 * 1024 * 1024,
    formatDataFunctionIsAsync: true,
    formatDataFunction: async item => {
      return new Promise((resolve, reject) => {
        resolve({
          name: item._file.name,
          length: item._file.size,
          contentType: item._file.type,
          date: new Date()
        });
      });
    }
  });




  onFileSelected(input) {
    if (!(this.filterAllowedType.indexOf(input.target.files[0].type) > -1)) {
      let msg: string = "";
      msg = this.ts.trPK("general", "notSupportFile");
      this.cs.presentAlert(msg);
      return;
    } // todo: show alert that you tried uploading wrong files
    else {
      const file = input.target.files[0];
      this.selectedFile = input.target.files;


      this.getBase64(file).then(data =>
        this.pushObject(data, file.name, file.type)
      );
    }
  }

  getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }

  pushObject(fileData, name, type) {

    this.indexLastObj++;
    try {
      let array = name.split(".");
      let attachType: string = array[array.length - 1];

      this.addAttachRequest.push({
        AttachmentID: this.indexLastObj,
        ContentType: 'image/' + attachType, //type.split('/')[1],
        Base64Data: fileData.split(",")[1],
        FileName: name, //.split('.')[0],

      });
    } catch (e) { }
  }

  removeFile(objectitem) {
    let objIndex1 = this.uploader.queue.findIndex(item => item == objectitem);
    this.uploader.queue.splice(objIndex1, 1);
    let objIndex = this.addAttachRequest.findIndex(
      item => item.AttachmentID == objectitem.AttachmentID
    );
    this.addAttachRequest.splice(objIndex, 1);
  }
  getImgContent(imgFile): SafeUrl {
    return this.sanitizer.bypassSecurityTrustUrl(imgFile);
  }

  createItemForSale() {

    var authUser = this.authService.getAuthenticatedRequest();
    this.cs.startLoading();
    // var request = new FormData();
    // request.append('title', this.itemInfo);
    // request.append('title_Ar', this.itemInfo);
    // request.append('categoryID', this.selectedCategory.categoryID);
    // request.append('description', this.itemDescription);
    // request.append('description_Ar', this.itemDescription);
    // request.append('employeeNumber', authUser.P_USER_NAME);
    // request.append('quotePrice', this.itemPrice);
    // request.append('isActive', 'true');
    // request.append('regionID', this.regionID);
    // request.append('status', this.itemCondition);
    // console.log(this.selectedFile);
    // if (this.selectedFile && this.selectedFile !== undefined) {
    //   request.append('fileColl', this.addAttachRequest.toString());
    // }
    // request.append('Channel', authUser.Channel.toString());
    // request.append('LogInToken', authUser.LogInTokenID);
    // request.append('Token', authUser.TokenID);
    // request.append('EmployeeNumber', authUser.P_USER_NAME);
    // request.append('MobileNo', authUser.MobileNumber);
    var request = {
      "TokenID": authUser.LogInTokenID, "EmployeeNumber": authUser.P_USER_NAME, "ItgImageCollList": this.addAttachRequest,
      "ItgTitle": this.itemInfo,
      "ItgTitleAr": this.itemInfo,
      "ItgCategoryID": this.selectedCategory.categoryID,
      "ItgDescription": this.itemDescription,
      "ItgDescriptionAr": this.itemDescription,
      "ItgQuotePrice": this.itemPrice,
      "RegionID": this.regionID,
      "ItgIsActive": true,
      "ItgStatus": this.itemCondition
    }

    this.itemService.createItemForSale(request, () => { }, this.ts.trPK('general', 'retry')).subscribe((result: any) => {
      if (this.cs.validResponse(result)) {
        this.cs.stopLoading();

        this.cs.greenToastPK("general", "success-create");
        this.openItem();
      } else {
        this.cs.stopLoading();
        this.cs.redToastPK("general", "try-again");
      }


    })
  }
  setEditPage() {
    this.step = 2;
    this.selectedCategory = {
      categoryID: this.editItem.categoryID,
      title: this.editItem.categoryTitle,
      title_Ar: this.editItem.categoryTitle
    }
    this.itemInfo = this.editItem.title;
    this.itemDescription = this.editItem.description;
    this.itemPrice = this.editItem.quotePrice;
    this.regionID = this.editItem.regionID;
    this.itemCondition = this.editItem.status.toLowerCase();
    this.addAttachRequest = this.getAttachment(this.editItem.itemAttachments);
  }
  getAttachment(itemsArray) {
    let item = [];
    itemsArray.forEach(element => {

      item.push({
        attachmentId: element.attachmentId,
        ContentType: element.contentType,
        Base64Data: element.content,
        FileName: element.fileName,

      });
    });
    return item;
  }
  updateItemForSale() {

    var authUser = this.authService.getAuthenticatedRequest();
    this.cs.startLoading();
    var request = new FormData();
    request.append('itemSaleID', this.editItem.itemSaleID);
    request.append('title', this.itemInfo);
    request.append('title_Ar', this.itemInfo);
    request.append('categoryID', this.selectedCategory.categoryID);
    request.append('description', this.itemDescription);
    request.append('description_Ar', this.itemDescription);
    request.append('employeeNumber', authUser.P_USER_NAME);
    request.append('quotePrice', this.itemPrice);
    request.append('isActive', 'true');
    request.append('regionID', this.regionID);
    request.append('status', this.itemCondition);
    // console.log(this.selectedFile);
    // if (this.selectedFile && this.selectedFile !== undefined) {
    //   request.append('fileColl', this.selectedFile[0], this.selectedFile[0].name);
    // }
    request.append('Channel', authUser.Channel.toString());
    request.append('LogInToken', authUser.LogInTokenID);
    request.append('Token', authUser.TokenID);
    request.append('EmployeeNumber', authUser.P_USER_NAME);
    request.append('MobileNo', authUser.MobileNumber);


    this.itemService.updateItemForSale(request, () => { }, this.ts.trPK('general', 'retry')).subscribe((result: any) => {
      if (this.cs.validResponse(result)) {
        this.cs.stopLoading();

        this.cs.greenToastPK("general", "success-create");
        this.openItem();
      } else {
        this.cs.stopLoading();
        this.cs.redToastPK("general", "try-again");
      }


    })
  }
}
