import { WebviewTag } from 'electron';
import * as _ from 'lodash';
import React from 'react';
import { ItemTextService } from '../services';
import { PoeService } from '../services/poe.service';
import { LoginWebview } from './login-webview';
import { PriceListItem } from './price-list-item/price-list-item';

interface IState {
  showLogin: boolean;
  data: any;
}

export class Home extends React.Component<any, IState> {
  private webview: WebviewTag;

  constructor(props: any) {
    super(props);
    this.state = {
      showLogin: false,
      data: [],
    };
  }

  componentDidMount() {
    this.addWebviewListeners();
  }

  public addWebviewListeners() {
    this.webview = this.refs['webview'] as any;
    this.webview.addEventListener('dom-ready', () => {
      // this.webview.openDevTools();
    });

    this.webview.addEventListener('ipc-message', e => {
      if (e.channel === 'html-content') {
        const htmlContents = e.args[0];
        this.handleResponse(htmlContents);
      }
    });
  }

  public handleResponse(res: any) {
    const json = JSON.parse(res);

    if (json === null || json['error']) {
      this.setState({ showLogin: true });
    } else if (json.items) {
      const items = _.map(json.items, item => {
        item.fullText = ItemTextService.parseItem(item);
        return item;
      });

      this.setState({ showLogin: false, data: items });
      this.getItemPrice(items, 0);
    }
  }

  onLogin = () => {
    this.setState({ showLogin: false });
    this.webview.reload();
  };

  async getItemPrice(data: any[], index: number) {
    if (!data[index] || data !== this.state.data) {
      return;
    }

    console.log(data[index]);
    console.log(data[index].fullText + '\n\n\n');
    const res = await PoeService.priceCheck(data[index].fullText);
    if ((res.min && res.currency) || (res.currency_rec && res.min_price)) {
      const dataCopy: any = [...data];
      dataCopy[index].priceInfo = res;
      await new Promise(resolve => this.setState({ data: dataCopy }, resolve));
    }

    setTimeout(() => {
      this.getItemPrice(this.state.data, index + 1);
    }, 1000);
  }

  renderPriceList = (data: any[]) => {
    return data.map((item, index) => <PriceListItem data={item} key={index} />);
  };

  public render() {
    const { data, showLogin } = this.state;

    const url =
      'https://www.pathofexile.com/character-window/get-stash-items' +
      '?league=Incursion&tabs=1&tabIndex=0&accountName=DoctorCoctor';

    return (
      <div style={{ padding: '20px' }}>
        {showLogin && <LoginWebview onSuccess={this.onLogin} />}
        {data && this.renderPriceList(data)}
        {/* {data && <StashTab data={data} />} */}
        <webview
          ref="webview"
          partition="persist:poe"
          preload="ipc-renderer.js"
          src={url}
          style={{ opacity: 0, width: '0', height: '0' }}
        />
      </div>
    );
  }
}
