import 'package:checker/base/base_screen.dart';
import 'package:checker/db.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'dart:core';

import 'package:checker/resources.dart';
import 'package:checker/strings.dart';
import 'package:checker/common.dart';
import 'package:checker/consts.dart';
import 'package:checker/network.dart';
import 'package:checker/base/base_state.dart';
import 'package:checker/screens/purchase_success.dart';

/// Экран проведения покупки.
class PurchaseScreen extends BaseScreen {

  PurchaseScreen(helper, app, this.user, this.card) : super(helper, app);

  final String user;
  final String card;

  @override
  State createState() => new PurchaseScreenState<PurchaseScreen>(helper, app, user, card);
}

class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
  /// Объект, помогающий вручную изменять введенный пользователем текст.
  /// Используется для форматирования введенных пользователем данных
  /// (удаляет запрещенные символы до их отображаения).
  TextEditingController controller = new TextEditingController();

  PurchaseScreenState(SqliteHelper helper, String app, String userString, String card) {
    this.user = JSON.decode(userString);
    this.card = card;
    this.helper = helper;
    this.app = app;
  }

  @override
  Widget build(BuildContext ctx) {
    setState(() {
      requestLoyalty(user['loyalty_url']);
    });
    return getMainWidget();
  }

  bool purchaseInProgress = false;
  Map user;
  String card = '';
  String loyalty = '';
  String bonus = '';
  bool dataLoaded = false;

  @override
  Widget getScreenContent() {
    List<Widget> widgets = [];
    widgets.add(getValueWithDescription(
        StringsLocalization.buyer(),
        user['first_name'] == null ? '' : user['first_name']
    ));
    widgets.add(getValueWithDescription(StringsLocalization.card(), card));

    if (bonus.length > 0) {
      widgets.add(getValueWithDescription(StringsLocalization.bonus(), bonus));
    }

    widgets.add(getValueWithDescription(StringsLocalization.reward(), loyalty));
    widgets.add(getHintLabel());
    widgets.add(getInputField());
    widgets.add(wrapButton(getScreenMargins(36.0), getCompleteButton()));
    widgets.add(wrapButton(
        getScreenMargins(24.0),
        getScanButton(
            context,
            StringsLocalization.scan(),
            Resources.getPrimaryColor(app)
        )
    ));
    return new Column(children: <Widget>[
      new Expanded(
          child: new ListView(children: widgets))
    ]);
  }

  getScreenMargins(double top) {
    double side = 42.0;
    return new EdgeInsets.only(top: top, left: side, right: side);
  }

  getCompleteButton() {
    return buildRaisedButton(
        StringsLocalization.completePurchase(), () => onPurchaseClick());
  }

  Widget getScanButton(BuildContext context, String title, Color textColor) {
    return new Container(
        height: buttonHeight,
        child: new FlatButton(
            child: new Text(title, style: new TextStyle(color: textColor)),
            onPressed: () => startScanner(context, app, helper)),
        decoration: new BoxDecoration(
            border: new Border.all(
                color: Resources.getButtonColor(app), width: 1.0),
            borderRadius: new BorderRadius.all(new Radius.circular(4.0))));
  }

  @override
  String getTitle() {
    return StringsLocalization.carryingPurchase();
  }

  @override
  getHintString() {
    return StringsLocalization.sum();
  }

  @override
  getTextWidget() {
    return new TextField(
      keyboardType: TextInputType.number,
      decoration: new InputDecoration.collapsed(
          hintText: getHintString(),
          hintStyle: new TextStyle(color: greyTextColor, fontSize: 16.0)),
      controller: controller,
      onSubmitted: (String text) {
        setState(() {
          controller.text = _parseSum(text);
        });
      },
      textAlign: TextAlign.center,
      autofocus: true,
    );
  }

  requestLoyalty(String url) async {
    bool showBonus = await platform.invokeMethod('showBonus');
    if (await platform.invokeMethod('isOnline') && !this.dataLoaded) {
      getLoyaltyRequest(url, helper).then((response) {
        print(response);
        this.dataLoaded = true;
        setState(() {
          setBonuses(JSON.decode(response.body), showBonus );
        });
      }).catchError((error) {
        print(error.toString());
      });
    }
  }

  // TODO: Переделать, если потребуется
  String _cleanupNumber(String text) {
    String tmp = text
        .replaceAll(' ', '')
        .replaceAll('-', '')
        .replaceAll(',', '.')
        .replaceAll('..', '.');

    while (tmp.indexOf('..') != -1) {
      tmp = tmp.replaceAll('..', '.');
    }
    return tmp;
  }

  _parseSum(String input) {
    num sumTotal = 0.0;
    String text = _cleanupNumber(input);

    try {
      sumTotal = num.parse(text);
    } catch (exception) {
      print(exception);
      try {
        int idx = text.indexOf('.');
        String integerPart = text.substring(0, idx);
        String fractionalPart = text.substring(idx + 1, text.length);
        if (fractionalPart.length > 2) {
          fractionalPart = fractionalPart.substring(0, 2);
        }
        return '${integerPart}.${fractionalPart}';
      } catch (exception) {
        print(exception);
      }
    }
    return sumTotal.toStringAsFixed(2);
  }

  onPurchaseClick() {
    String val = _parseSum(controller.text);
    helper.getCurrency().then((currency) {
      print(currency.toString());
      showDialog(
          context: context,
          child: new AlertDialog(
              title: new Text(StringsLocalization.confirmation()),
              content:
              new Text(StringsLocalization.confirmPurchase(val, currency)),
              actions: <Widget>[
                new FlatButton(
                  child: new Text(StringsLocalization.no()),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
                new FlatButton(
                  child: new Text(StringsLocalization.yes()),
                  onPressed: () {
                    purchase(val);
                  },
                )
              ]));
    });
  }

  purchase(String sumTotal) async {
    if (await platform.invokeMethod('isOnline')) {
      if (!purchaseInProgress) {
        purchaseInProgress = true;

        String token = await helper.getToken();
        helper.getMerchantID().then((result) {
          helper.getCurrency().then((currency) {
            var body = {
              'doc_id': result,
              'curr_iso_code': currency.toString(),
              'commit': 'true',
              'sum_total': sumTotal
            };

            getPurchaseRequest(user['purchases_url'], body, token)
                .then((response) {
              print(response.body);
              Map parsedMap = JSON.decode(response.body);

              Navigator.of(context).pop();

              if (parsedMap.containsKey('errors')) {
                List<String> errors = parsedMap['errors'];
                Scaffold
                    .of(context)
                    .showSnackBar(new SnackBar(content: new Text(errors[0])));
              } else {
                pushRouteReplacement(
                    context,
                    new PurchaseSuccessScreen(
                        sumTotal,
                        user['first_name'] == null ? '' : user['first_name'],
                        helper,
                        app));
              }
            }).catchError((error) {
              purchaseInProgress = false;
              print(error.toString());
            });
          });
        });
      }
    }
  }

  void setBonuses(Map bonuses, bool showBonus) {
    print('kifio ' + bonuses['type']);
    if (bonuses['type'] == 'amount') {
      this.loyalty = '${user['discount']}%';
    } else {
      double loyaltyVal = (double.parse(bonuses['amount_to_bonus'][1]) /
          bonuses['amount_to_bonus'][0]) * 100;
      this.loyalty = '${loyaltyVal.toStringAsFixed(0)}%';
    }

    if (showBonus && (bonuses['type'] == 'bonus')) {
      this.bonus = '${user['bonus']}';
    }
    print('kifio ' + this.loyalty);
    print('bonus ' + this.bonus);
  }
}
