from flask import render_template, request, flash
from nanobrok.models import DeviceInfo, User
import uuid, jwt
from dynaconf import settings
from nanobrok.ext.database import db
from flask_login import login_required


# This file is part of the Nanobrok Open Source Project.
# nanobrok is licensed under the Apache 2.0.

# Copyright 2021 p0cL4bs Team - Marcos Bomfim (mh4x0f)

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


@login_required
def sync_index():
    user_mobile = User.query.one_or_none()
    # TODO: implement option in user model for control intial access
    if request.method == "POST":
        if user_mobile:
            if user_mobile.is_connected:
                user_mobile.is_authenticated = True
                db.session.add(user_mobile)
                db.session.commit()
                flash(
                    f"The device {user_mobile.deviceInfo.manufacturer} { user_mobile.deviceInfo.model } has connected successfully."
                )

    if not user_mobile:
        user_mobile = User(public_id=str(uuid.uuid4()))
        user_mobile.deviceInfo = DeviceInfo()
        db.session.add(user_mobile)
        db.session.commit()

    token_jwt = jwt.encode(
        {"public_id": user_mobile.public_id},
        settings.SECRET_KEY,
    )
    return render_template(
        "pages/sync/index.html",
        token_jwt=token_jwt.decode("UTF-8"),
        user=user_mobile,
    )
