# -*- coding: utf-8 -*-

from __future__ import division

from django.contrib.auth.hashers import check_password, make_password
from django_response import response
from logit import logit

from mch.models import BrandInfo, DistributorInfo, LatestAppInfo, ModelInfo, OperatorInfo
from utils.error.errno_utils import OperatorStatusCode


@logit
def login_api(request):
    phone = request.POST.get('phone', '')
    password = request.POST.get('password', '')

    try:
        operator = OperatorInfo.objects.get(phone=phone, status=True)
    except OperatorInfo.DoesNotExist:
        return response(OperatorStatusCode.OPERATOR_NOT_FOUND)

    if operator.user_status == OperatorInfo.DISABLED:
        return response(OperatorStatusCode.OPERATOR_NOT_ACTIVATED)

    if not check_password(password, operator.encryption):
        return response(OperatorStatusCode.OPERATOR_PASSWORD_ERROR)

    brands = BrandInfo.objects.filter(brand_id=operator.brand_id, status=True).order_by('position')
    brands = [brand.data for brand in brands]

    models = ModelInfo.objects.filter(brand_id=operator.brand_id, status=True).order_by('position')
    models = [model.data for model in models]

    distributors = DistributorInfo.objects.filter(brand_id=operator.brand_id, status=True).order_by('position')
    distributors = [distributor.data for distributor in distributors]

    return response(200, data={
        'brands': brands,
        'models': models,
        'distributors': distributors,
    })


@logit
def brands_list(request):
    brands = BrandInfo.objects.filter(status=True).order_by('position')
    brands = [brand.data for brand in brands]

    return response(200, data={
        'brands': brands,
    })


@logit
def models_list(request):
    models = ModelInfo.objects.filter(status=True).order_by('position')
    models = [model.data for model in models]

    return response(200, data={
        'models': models,
    })


@logit
def distributors_list(request):
    distributors = DistributorInfo.objects.filter(status=True).order_by('position')
    distributors = [distributor.data for distributor in distributors]

    return response(200, data={
        'distributors': distributors,
    })


@logit
def upgrade_api(request):
    """ APP 升级 """
    try:
        appinfo = LatestAppInfo.objects.filter(status=True)[0].adr
    except IndexError:
        appinfo = {
            'latest_version_code': '',
            'latest_version_name': '',
            'latest_url': '',
        }

    return response(200, 'Get Latest App Success', u'获取最新版信息成功', {
        'appinfo': appinfo,
    })
