import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'dart:math';
import 'dart:async';

import '../provider/data.dart';
import '../utils/random_pick_category.dart';
import '../utils/random_pick_letter.dart';

class Home extends StatelessWidget {
  static const String id = 'home';

  String _randomLetter = '';
  String _randomCategory = '';
  Timer _timer;
  int _countdownStart = 10;

  Future<void> startMiniGame(Data myProvider) async {
    if (myProvider.countdown == 0) {
      pickCategory(myProvider);
      pickLetter(myProvider);
      startTimer(myProvider);
    }
  }

  Future<void> startTimer(Data myProvider) async {
    const oneSec = const Duration(seconds: 1);
    if (_timer != null) {
      dispose();
    }
    _countdownStart = 10;
    myProvider.updateCountdown = _countdownStart;
    _timer = new Timer.periodic(
      oneSec,
      (Timer timer) {
        if (_countdownStart == 0) {
          timer.cancel();
        } else {
          _countdownStart--;
          myProvider.updateCountdown = _countdownStart;
        }
      },
    );
  }

  @override
  void dispose() {
    _timer.cancel();
  }

  Future<void> pickCategory(Data myProvider) async {
    myProvider.searchingCategory = true;
    RandomPickCategory randomPickCategory;
    int attempts = 0;
    do {
      randomPickCategory = RandomPickCategory();
      await randomPickCategory.init();
      if (randomPickCategory.category != null) {
        myProvider.updateCategory = randomPickCategory.category;
        myProvider.searchingCategory = false;
        break;
      }
      attempts++;
    } while (attempts < 3);
  }

  Future<void> pickLetter(Data myProvider) async {
    myProvider.searchingLetter = true;
    RandomPickLetter randomPickLetter;
    int attempts = 0;
    do {
      randomPickLetter = RandomPickLetter();
      await randomPickLetter.init();
      if (randomPickLetter.letter != null) {
        myProvider.updateLetter = randomPickLetter.letter;
        myProvider.searchingLetter = false;
        break;
      }
      attempts++;
    } while (attempts < 3);
  }

  Color darken(Color baseColor, {double amount = 0.2}) {
    final hsl = HSLColor.fromColor(baseColor);
    final hslDark = hsl.withLightness((hsl.lightness - amount).clamp(0.0, 1.0));
    return hslDark.toColor();
  }

  Container _buildPickedLetterContainer(Data myProvider, Color backgroundColor) {
    Color borderColor = darken(backgroundColor);

    return Container(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FlatButton(
            onPressed: () => pickLetter(myProvider),
            child: Text("🔀"),
          ),
          myProvider.letter == '' ? null : Container(
            margin: EdgeInsets.all(5),
            padding: EdgeInsets.all(5),
            decoration: BoxDecoration(
              color: backgroundColor,
              borderRadius: BorderRadius.circular(4),
              border: Border.all(
                color: borderColor,
                width: 4,
              ),
            ),
            child: Text(
              myProvider.letter,
              style: TextStyle(
                fontSize: 40,
                fontWeight: FontWeight.w600,
                color: Colors.black,
              ),
            ),
          ),
        ],
      ),
    );
  }


  Container _buildPickedCategoryContainer(Data myProvider, Color backgroundColor) {
    Color borderColor = darken(backgroundColor);

    return Container(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FlatButton(
            onPressed: () => pickCategory(myProvider),
            child: Text("🔀"),
          ),
          myProvider.category == '' ? null : Container(
            margin: EdgeInsets.all(5),
            padding: EdgeInsets.all(5),
            decoration: BoxDecoration(
              color: backgroundColor,
              borderRadius: BorderRadius.circular(4),
              border: Border.all(
                color: borderColor,
                width: 4,
              ),
            ),
            child: Text(
              myProvider.category,
              style: TextStyle(
                fontSize: 40,
                fontWeight: FontWeight.w600,
                color: Colors.black,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Container _buildMiniGameContainer(Data myProvider, Color backgroundColor) {
    Color borderColor = darken(backgroundColor);

    return Container(
      margin: EdgeInsets.all(5),
      padding: EdgeInsets.all(5),
      decoration: BoxDecoration(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(4),
        border: Border.all(
          color: borderColor,
          width: 4,
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FlatButton(
            onPressed: (myProvider.countdown != 0) ? null : () => startMiniGame(myProvider),
            padding: EdgeInsets.all(10.0),
            child: Text(
              (myProvider.countdown != 0) ? myProvider.countdown.toString() : '🎲',
              style: TextStyle(
                fontSize: 50,
                fontWeight: FontWeight.w600,
                color: Colors.black,
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    Data _myProvider = Provider.of<Data>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Petit bac'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _buildPickedLetterContainer(_myProvider, Colors.orange),
            SizedBox(height: 20),
            _buildPickedCategoryContainer(_myProvider, Colors.green),
            SizedBox(height: 40),
            _buildMiniGameContainer(_myProvider, Colors.blue),
          ],
        ),
      ),
    );
  }
}