# Path: utils/file_operator.py
# def file_upload_save_process(request):
#     f = request.FILES["file"]
#     name, filetype = split_file_name(UploadedFile(f).name)
#     obj = ProcessedFile()
#     obj.title = name
#     obj.file_type = filetype
#     obj.file_obj = f
#     obj.save()
# 
#     return obj
# 
# Path: chemistry/util.py
# def singletask_details(pid):
#     from chemistry.tasks import has_temperature
#     single_task = get_object_or_404(SingleTask, pid=pid)
#     if not has_temperature(single_task.model.desc):
#         single_task.temperature = '--'
#     single_task.result_value, single_task.hi, single_task.hx, single_task.degrade = get_singletask_area(single_task.results)
#     try:
#         local_search_id = single_task.file_obj.local_search_id
#         if local_search_id:
#             local_search = ChemInfoLocal.objects.get(id=local_search_id)
#         else:
#             local_search = None
#     except Exception:
#         chemistry_logger.exception('failed to get cheminfo by local_search_id')
#         local_search = None
# 
#     return dict(singletask=single_task,
#                 search_engine=local_search)
# 
# def suitetask_details(sid):
#     from chemistry.tasks import has_temperature
#     suitetask = get_object_or_404(SuiteTask, sid=sid)
#     single_lists = SingleTask.objects.filter(sid=sid, is_hide=False)
# 
#     for s in single_lists:
#         if not has_temperature(s.model.desc):
#             s.temperature = '--'
#         s.result_value, s.hi, s.hx, s.degrade = get_singletask_area(s.results)
# 
#     return dict(suitetask=suitetask,
#                 single_lists=single_lists)
# 
# def submit_calculate_task(user, smile=None, draw_mol_data=None,
#                           task_notes=None, task_name=None,
#                           files_id_list=None, models=None,
#                           local_search_id=None):
# 
#     chemistry_logger.info("smile: %s" % smile)
#     chemistry_logger.info("draw_mol_data: %s" % draw_mol_data)
#     chemistry_logger.info("files_id_list: %s" % files_id_list)
#     chemistry_logger.info("models: %s" % models)
# 
#     tasks_num = calculate_tasks(files_id_list, smile, draw_mol_data, models)
# 
#     if tasks_num == 0:
#         status = False
#         info = "请至少选择一种输入方式和计算模型!"
#         id = None
#         return (status, info, id)
# 
#     try:
#         s = SuiteTask()
#         s.sid = id = str(uuid.uuid4())
#         s.user = UserProfile.objects.get(user=user)
#         s.total_tasks = tasks_num
#         s.has_finished_tasks = 0
#         s.start_time = utils.get_real_now()
#         s.name = task_name
#         s.notes = task_notes
#         s.models_str, s.models_category_str = parse_models(models)
#         s.status = StatusCategory.objects.get(category=STATUS_WORKING)
#         s.email = user.email
#         s.save()
#         
#         chemistry_logger.info('~~~~~~~~ s:%s' % s.start_time)
# 
#         generate_calculate_task.delay(models, smile, draw_mol_data,
#                                       files_id_list, id, local_search_id)
#     except:
#         chemistry_logger.exception('failed to generate suite_task')
#         s.delete()
#         status = False
#         info = "计算任务添加不成功，将重试或联系网站管理员!"
#         id = None
#     else:
#         status = True
#         info = "恭喜,计算任务已经提交!"
# 
#     return (status, info, id)
# 
# @simple_search_output
# def search_cheminfo_local(query, start=0, limit=10):
#     #TODO: 加入中文名称搜索
#     #Q(common_name_ch__contains=query['common_name_ch']) |
#     q = Q(cas=query['cas'].strip())
#     if query['smile']:
#         q |= Q(smiles=query['smile'].strip())
#     if query['common_name_en']:
#         q |= Q(einecs_name__contains=query['common_name_en'].strip())
# 
#     results = ChemInfoLocal.objects.filter(q)[start:(start + limit)]
#     return results


import json
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponseForbidden
from utils import make_json_response, basic_auth_api
from utils.file_operator import file_upload_save_process
from chemistry.util import (singletask_details, suitetask_details,
                            submit_calculate_task, search_cheminfo_local)
from chemistry.models import SuiteTask
@csrf_exempt
def smile_search(request):
    if not basic_auth_api(request):
        return HttpResponseForbidden()

    query = dict(cas=request.POST.get('cas'),
                 smile=request.POST.get('smile'),
                 common_name_ch=request.POST.get('common_name_ch'),
                 common_name_en=request.POST.get('common_name_en'))

    # TODO: 开启分页
    start = int(request.POST.get('start', 0))
    limit = int(request.POST.get('limit', 10))

    # TODO: 目前只是使用本地搜索，未来重新开启第三方search API
    #results_chemspider = search_cheminfo(query, start, limit)
    results = search_cheminfo_local(query, start, limit)

    return make_json_response(results)


@require_POST
@csrf_exempt
def mol_upload(request):
    if not basic_auth_api(request):
        return HttpResponseForbidden()

    if request.method == "POST" and request.FILES:
        try:
            f = file_upload_save_process(request)

# Path: utils/file_operator.py
# def file_upload_save_process(request):
#     f = request.FILES["file"]
#     name, filetype = split_file_name(UploadedFile(f).name)
#     obj = ProcessedFile()
#     obj.title = name
#     obj.file_type = filetype
#     obj.file_obj = f
#     obj.save()
# 
#     return obj
# 
# Path: chemistry/util.py
# def singletask_details(pid):
#     from chemistry.tasks import has_temperature
#     single_task = get_object_or_404(SingleTask, pid=pid)
#     if not has_temperature(single_task.model.desc):
#         single_task.temperature = '--'
#     single_task.result_value, single_task.hi, single_task.hx, single_task.degrade = get_singletask_area(single_task.results)
#     try:
#         local_search_id = single_task.file_obj.local_search_id
#         if local_search_id:
#             local_search = ChemInfoLocal.objects.get(id=local_search_id)
#         else:
#             local_search = None
#     except Exception:
#         chemistry_logger.exception('failed to get cheminfo by local_search_id')
#         local_search = None
# 
#     return dict(singletask=single_task,
#                 search_engine=local_search)
# 
# def suitetask_details(sid):
#     from chemistry.tasks import has_temperature
#     suitetask = get_object_or_404(SuiteTask, sid=sid)
#     single_lists = SingleTask.objects.filter(sid=sid, is_hide=False)
# 
#     for s in single_lists:
#         if not has_temperature(s.model.desc):
#             s.temperature = '--'
#         s.result_value, s.hi, s.hx, s.degrade = get_singletask_area(s.results)
# 
#     return dict(suitetask=suitetask,
#                 single_lists=single_lists)
# 
# def submit_calculate_task(user, smile=None, draw_mol_data=None,
#                           task_notes=None, task_name=None,
#                           files_id_list=None, models=None,
#                           local_search_id=None):
# 
#     chemistry_logger.info("smile: %s" % smile)
#     chemistry_logger.info("draw_mol_data: %s" % draw_mol_data)
#     chemistry_logger.info("files_id_list: %s" % files_id_list)
#     chemistry_logger.info("models: %s" % models)
# 
#     tasks_num = calculate_tasks(files_id_list, smile, draw_mol_data, models)
# 
#     if tasks_num == 0:
#         status = False
#         info = "请至少选择一种输入方式和计算模型!"
#         id = None
#         return (status, info, id)
# 
#     try:
#         s = SuiteTask()
#         s.sid = id = str(uuid.uuid4())
#         s.user = UserProfile.objects.get(user=user)
#         s.total_tasks = tasks_num
#         s.has_finished_tasks = 0
#         s.start_time = utils.get_real_now()
#         s.name = task_name
#         s.notes = task_notes
#         s.models_str, s.models_category_str = parse_models(models)
#         s.status = StatusCategory.objects.get(category=STATUS_WORKING)
#         s.email = user.email
#         s.save()
#         
#         chemistry_logger.info('~~~~~~~~ s:%s' % s.start_time)
# 
#         generate_calculate_task.delay(models, smile, draw_mol_data,
#                                       files_id_list, id, local_search_id)
#     except:
#         chemistry_logger.exception('failed to generate suite_task')
#         s.delete()
#         status = False
#         info = "计算任务添加不成功，将重试或联系网站管理员!"
#         id = None
#     else:
#         status = True
#         info = "恭喜,计算任务已经提交!"
# 
#     return (status, info, id)
# 
# @simple_search_output
# def search_cheminfo_local(query, start=0, limit=10):
#     #TODO: 加入中文名称搜索
#     #Q(common_name_ch__contains=query['common_name_ch']) |
#     q = Q(cas=query['cas'].strip())
#     if query['smile']:
#         q |= Q(smiles=query['smile'].strip())
#     if query['common_name_en']:
#         q |= Q(einecs_name__contains=query['common_name_en'].strip())
# 
#     results = ChemInfoLocal.objects.filter(q)[start:(start + limit)]
#     return results


# Path: chemistry/api_views.py
import json
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponseForbidden
from utils import make_json_response, basic_auth_api
from utils.file_operator import file_upload_save_process
from chemistry.util import (singletask_details, suitetask_details,
                            submit_calculate_task, search_cheminfo_local)
from chemistry.models import SuiteTask

@csrf_exempt
def smile_search(request):
    if not basic_auth_api(request):
        return HttpResponseForbidden()

    query = dict(cas=request.POST.get('cas'),
                 smile=request.POST.get('smile'),
                 common_name_ch=request.POST.get('common_name_ch'),
                 common_name_en=request.POST.get('common_name_en'))

    # TODO: 开启分页
    start = int(request.POST.get('start', 0))
    limit = int(request.POST.get('limit', 10))

    # TODO: 目前只是使用本地搜索，未来重新开启第三方search API
    #results_chemspider = search_cheminfo(query, start, limit)
    results = search_cheminfo_local(query, start, limit)

    return make_json_response(results)


@require_POST
@csrf_exempt
def mol_upload(request):
    if not basic_auth_api(request):
        return HttpResponseForbidden()

    if request.method == "POST" and request.FILES:
        try:
            f = file_upload_save_process(request)

        except Exception as err: