# Path: app/api/models/LXCFileManager.py
# class LXCFileManager(LXDModule):
# 
#     def __init__(self, input):
#         logging.info('Connecting to LXD')
#         super().__init__()
#         self.input = input
# 
#     def list(self):
#         pass
# 
#     def download(self):
#         try:
#             logging.info('Download file {} from container {}'.format(self.input.get('path'), self.input.get('name')))
#             container = self.client.instances.get(self.input.get('name'))
#             file = container.files.get(self.input.get('path'))
#             return file
#         except Exception as e:
#             logging.error('Download file {} from container {} failed.'.format(self.input.get('path'), self.input.get('name')))
#             logging.exception(e)
#             raise ValueError(e)
# 
#     def push(self):
#         try:
#             logging.info('Push file {} to container {}'.format(self.input.get('path'), self.input.get('name')))
#             container = self.client.instances.get(self.input.get('name'))
#             return container.files.put(self.input.get('path'), self.input.get('file'))
#         except Exception as e:
#             logging.error('Push file {} to container {} failed.'.format(self.input.get('path'), self.input.get('name')))
#             logging.exception(e)
#             raise ValueError(e)
# 
# 
#     def delete(self):
#         try:
#             logging.info('Delete file {} from container {}'.format(self.input.get('path'), self.input.get('name')))
#             container = self.client.instances.get(self.input.get('name'))
#             return container.files.delete(self.input.get('path'))
#         except Exception as e:
#             logging.error('Delete file {} from container {} failed.'.format(self.input.get('path'), self.input.get('name')))
#             logging.exception(e)
#             raise ValueError(e)
# 
# Path: app/api/utils/response.py
# def replySuccess(data=None, message='Success'):
# def replyFailed(data=None, message='Failed', status=403):
# def reply(data=None, message='Success', status=200):


from flask import Blueprint, request, send_file
from flask import jsonify
from flask_jwt_extended import jwt_required
from app.api.models.LXCFileManager import LXCFileManager
from app.api.utils import response
import io
import json
    input['path'] = path

    try:
        try:
            #Folder
            fileManager = LXCFileManager(input)
            items = json.loads(fileManager.download().decode('utf-8'))['metadata']
            return response.replyFailed('Please select a file for download')
        except:
            #File
            fileManager = LXCFileManager(input)
            file = io.BytesIO(fileManager.download())
            return send_file(file, attachment_filename=path.rsplit("/").pop(), mimetype="application/octet-stream", as_attachment=True)

    except ValueError as ex:
        return response.replyFailed(ex.__str__())


@file_manager_api.route('/container/<string:name>', methods=['POST'])
@jwt_required
def upload_file(name):
    input = None
    try:
        file = request.files.get('file')
        input = {
            'name':name,
            'path':request.form.get('path')+file.filename,
            'file':file
        }
    except:

# Path: app/api/models/LXCFileManager.py
# class LXCFileManager(LXDModule):
# 
#     def __init__(self, input):
#         logging.info('Connecting to LXD')
#         super().__init__()
#         self.input = input
# 
#     def list(self):
#         pass
# 
#     def download(self):
#         try:
#             logging.info('Download file {} from container {}'.format(self.input.get('path'), self.input.get('name')))
#             container = self.client.instances.get(self.input.get('name'))
#             file = container.files.get(self.input.get('path'))
#             return file
#         except Exception as e:
#             logging.error('Download file {} from container {} failed.'.format(self.input.get('path'), self.input.get('name')))
#             logging.exception(e)
#             raise ValueError(e)
# 
#     def push(self):
#         try:
#             logging.info('Push file {} to container {}'.format(self.input.get('path'), self.input.get('name')))
#             container = self.client.instances.get(self.input.get('name'))
#             return container.files.put(self.input.get('path'), self.input.get('file'))
#         except Exception as e:
#             logging.error('Push file {} to container {} failed.'.format(self.input.get('path'), self.input.get('name')))
#             logging.exception(e)
#             raise ValueError(e)
# 
# 
#     def delete(self):
#         try:
#             logging.info('Delete file {} from container {}'.format(self.input.get('path'), self.input.get('name')))
#             container = self.client.instances.get(self.input.get('name'))
#             return container.files.delete(self.input.get('path'))
#         except Exception as e:
#             logging.error('Delete file {} from container {} failed.'.format(self.input.get('path'), self.input.get('name')))
#             logging.exception(e)
#             raise ValueError(e)
# 
# Path: app/api/utils/response.py
# def replySuccess(data=None, message='Success'):
# def replyFailed(data=None, message='Failed', status=403):
# def reply(data=None, message='Success', status=200):


# Path: app/api/controllers/fileManager.py
from flask import Blueprint, request, send_file
from flask import jsonify
from flask_jwt_extended import jwt_required
from app.api.models.LXCFileManager import LXCFileManager
from app.api.utils import response
import io
import json

    input['path'] = path

    try:
        try:
            #Folder
            fileManager = LXCFileManager(input)
            items = json.loads(fileManager.download().decode('utf-8'))['metadata']
            return response.replyFailed('Please select a file for download')
        except:
            #File
            fileManager = LXCFileManager(input)
            file = io.BytesIO(fileManager.download())
            return send_file(file, attachment_filename=path.rsplit("/").pop(), mimetype="application/octet-stream", as_attachment=True)

    except ValueError as ex:
        return response.replyFailed(ex.__str__())


@file_manager_api.route('/container/<string:name>', methods=['POST'])
@jwt_required
def upload_file(name):
    input = None
    try:
        file = request.files.get('file')
        input = {
            'name':name,
            'path':request.form.get('path')+file.filename,
            'file':file
        }
    except:

        return  response.replyFailed(message='Missing one the required fields: [path,file]')