from django.http import HttpResponse, JsonResponse
from dls.models import (
    User, 
    AssignVessel, 
    SurveyReport, 
    TestTable, 
    FenderingImages, 
    BulwarksImage, 
    BulwarksDeck, 
    CargoRailsImage, 
    CargoRails, 
    DeckFittingsImage, 
    DeckFittings, 
    GroundTackleImage,
    HullCompImage,
    HullCompTank,
    HullCompCapacity,
    HullCompBullet,
    DeckHouseImage,
    PilotHouseImage,
    SuperStructureImage,
    MachinaryImage,
    SafetyEquipmentImage,
    BerthingCompartments,
    Galley,
    MessDecks,
    Laundry,
    Hospital,
    RecreationRoom,
    TheaterRoom,
    HeloReceptionRoom,
    PublicSanitaryFacilities,
    OtherDeckHouseCategory,
    PilothouseEquipments,
    AuxiliaryMachinery,
    Recommendations,
    SurveyReportBarge,
    BowCompartment,
    StarboardSide,
    SternCompartment,
    PortSide,
) 

from django.contrib.auth import authenticate
from rest_framework.decorators import api_view
from rest_framework.authtoken.models import Token
from rest_framework.permissions import IsAuthenticated

from rest_framework.decorators import permission_classes, parser_classes
from rest_framework.parsers import FileUploadParser, MultiPartParser, FormParser
from django.core.files.storage import FileSystemStorage


from .token import account_activation_token
from django.conf import settings
from datetime import datetime, timedelta
import base64
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
import time
import json
from django.core import serializers
from django.conf import settings

from .forms import (
    TestForm
)
import uuid
import boto3
from boto3.s3.transfer import S3Transfer
import requests

from .tasks import text_to_speech
from dls.global_configuration import GlobalConfiguration
import smtplib  
import email.utils
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import random
import ast

# Create your views here.

@csrf_exempt
def user_login(request):
    email = request.POST.get("email")
    password = request.POST.get("password")

    user = authenticate(email=email, password=password)
    if not user:
        return JsonResponse({"message": "Email or password is invalid.", "code": "500", "token": ""})
    else:
        if not user.is_active:
            return JsonResponse({"message": "User not activated. Please contact administrator", "code": "404", "token": ""})

    token, _ = Token.objects.get_or_create(user=user)
    return JsonResponse({"message": "", "token": token.key, "code": "200", "user_id":user.id})

@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def user_profile(request):
    user_arr = []
    user_details = User.objects.get(pk=request.user.id)
    filename = settings.MEDIA_ROOT + str(user_details.avator)
    with open(filename, "rb") as imageFile:
        str_1 = base64.b64encode(imageFile.read())
    user_arr.append({
        "id": user_details.id,
        "first_name": user_details.first_name,
        "last_name": user_details.last_name,
        "avator": str(str_1, 'utf-8'),
        "address": user_details.address,
        "mobile_no": user_details.mobile_no,
        "city": user_details.city,
        "state": user_details.state
    })
    return JsonResponse({"code": "200",
        "user_details": user_arr
    })

@api_view(['POST'])
@permission_classes(( ))
@csrf_exempt
def forget_password(request):
    email = request.POST.get('email')
    user = User.objects.filter(email=email)
    code = '200'
    status = ''
    if user:
        user = user[0]
        r = lambda: random.randint(1000,9999)
        otp = r()
        user.otp = otp
        user.save()
        body_text = ''
        body_html = """<html>
                        <head></head>
                        <body>
                        <h1>Use this otp to change your password.</h1>
                        <p>Seems like you forgot your password for DLS account.\r\nThis is your OTP : """+str(otp)+"""</p>
                        </body>
                        </html>
                    """
        GlobalConfiguration.send_email('Dufour Laskay & Strouse', email, 'OTP for forgot password', body_text, body_html)
    else:
        code = '300'
        status = 'Invalid Email Address'

    return JsonResponse({'code': code, 'message':status})

@api_view(['POST'])
@permission_classes(( ))
@csrf_exempt
def update_password(request):
    email = request.POST.get('email')
    password = request.POST.get('password')
    otp = request.POST.get('otp')
    user = User.objects.filter(email=email)
    code = '200'
    status = ''
    if user:
        user = user[0]
        if str(user.otp) == str(otp):
            user.set_password(password)
            user.save()
        else:
            code = '300'
            status = 'Invalid OTP'
    else:
        code = '300'
        status = 'Invalid Email Address'
    return JsonResponse({'code': code, 'message':status})

@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def user_assignment(request):
    assignment_arr = []
    assignment_arr_future = []
    assignment_arr_prev = []
    today = datetime.now().date()
    assignment_details = AssignVessel.objects.filter(user_id=request.user.id).filter(assignment__start_date=today).filter(stage_completed_id__lte=4)
    for asg in assignment_details:
        assignment_arr.append({
            "vessel_name": asg.vessel_name,
            "assign_vessel_id": asg.id,
            "vessel_type_id": asg.vessel_type_id,
            "vessel_stage_id": asg.stage_completed_id
        })
    
    assignment_details_future = AssignVessel.objects.filter(user_id=request.user.id).filter(assignment__start_date__gt=today).filter(stage_completed_id__lte=4)
    for asg in assignment_details_future:
        assignment_arr_future.append({
            "vessel_name": asg.vessel_name,
            "assign_vessel_id": asg.id,
            "vessel_type_id": asg.vessel_type_id,
            "vessel_stage_id": asg.stage_completed_id
        })
    assignment_details_prev = AssignVessel.objects.filter(user_id=request.user.id).filter(assignment__start_date__lt=today).filter(status=1).filter(stage_completed_id__lte=4)
    for asg in assignment_details_prev:
        assignment_arr_prev.append({
            "vessel_name": asg.vessel_name,
            "assign_vessel_id": asg.id,
            "vessel_type_id": asg.vessel_type_id,
            "vessel_stage_id": asg.stage_completed_id
        })
    return JsonResponse({"code": "200",
        "assignment_details": assignment_arr,
        "assignment_arr_future": assignment_arr_future,
        "assignment_arr_prev": assignment_arr_prev
    })


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def user_vessel_details(request):
    vessel_details_arr = []
    vessel_details = AssignVessel.objects.filter(user_id=request.user.id).filter(id=request.POST.get('assign_vessel_id')).filter(vessel_type_id=request.POST.get('vessel_type_id'))
    for vd in vessel_details:
        vessel_details_arr.append({
            "state": vd.street_address,
            "city": vd.city,
            "state": vd.state,
            "account_of": vd.account_of,
            "operator": vd.operator,
            "owner": vd.owner,
            "vessel_name": vd.vessel_name,
            "vessel_type_name": vd.vessel_type.type_name,
            "requested_by": vd.requested_by,
            "id": vd.id,
            'form_type': vd.form_type
        })
    return JsonResponse({"code": "200",
        "vessel_details_arr": vessel_details_arr
    })


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def update_user_vessel_details(request):
    obj = AssignVessel.objects.get(pk=int(request.POST.get('id')))
    obj.street_address = request.POST.get('street_address' , '')
    obj.account_of = request.POST.get('account_of', '')
    obj.operator = request.POST.get('operator', '')
    obj.owner = request.POST.get('owner', '')
    obj.vessel_name = request.POST.get('vessel_name', '')
    obj.vessel_type_name = request.POST.get('vessel_type_name', '')
    obj.requested_by = request.POST.get('requested_by', '')

    if obj.stage_completed_id == 3:
        obj.stage_completed_id = 4 #siddhartha-06-11
        obj.vessel_deployed = datetime.now() #siddhartha-06-11
        #obj.survey_complate = datetime.now() #siddhartha-06-11

    obj.save()

    if request.POST.get('form_type') == "0":
        survey_report = SurveyReport.objects.filter(assigned_vessel_id=int(request.POST.get('id')))
        if survey_report:
            survey_report[0].survey_location = request.POST.get('street_address' , '')
            survey_report[0].save()            
        survey_report_id = survey_report[0].id if survey_report else ''
    else:
        survey_report = SurveyReportBarge.objects.filter(assigned_vessel_id=int(request.POST.get('id')))
        survey_report_id = survey_report[0].id if survey_report else ''

    return JsonResponse({"code": "200",
        "msg": "Information updated successfully",
        "survey_report_id": survey_report_id
    })



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_details(request):
    fendering_images_arr = []
    bulwarks_image_arr = []
    cargo_rails_images_arr = []
    deck_fitting_images_arr = []
    ground_tackle_images_arr = []
    hull_comp_images_arr = []
    deck_house_image_arr = []
    pilot_house_image_arr = []
    super_structure_image_arr = []
    machinary_image_arr = []
    safety_equipment_image_arr = []
    
    df_deck_name_arr = []
    df_fittings_arr = []
    df_number_arr = []
    df_size_arr = []
    df_location_arr = []
    df_deck_name_other_arr = []
    df_fittings_other_arr = []

    bulwarks_deck_name = []
    bulwarks_deck_height = []
    bulwarks_deck_type = []
    bulwarks_deck_material = []
    bulwarks_deck_cap = []
    bulwarks_deck_cap_dimen = []
    bulwarks_deck_stiffeners = []
    bulwarks_deck_cap_dimen_other = []
    bulwarks_deck_name_other = []
    bulwarks_deck_stiffeners_other = []

    cargorails_deck_name = []
    cargorails_deck_height = []
    cargorails_deck_construction = []
    cargorails_deck_cap = []
    cargorails_deck_cap_dimen = []
    cargorails_deck_stiffeners = []
    cargorails_deck_cap_dimen_other = []
    cargorails_deck_name_other = []
    cargorails_deck_material = []

    hc_tanktype = []
    hc_tanktypefillings = []
    hc_tanktypevents = []

    hc_capacitytype = []
    hc_capacitytypefillings = []
    hc_capacitytypevents = []

    dh_bc_outer_bullet = []
    dh_bc_inner_bullet = []

    dh_g_outer_bullet = []
    dh_g_inner_bullet = []

    dh_md_outer_bullet = []
    dh_md_inner_bullet = []

    dh_l_outer_bullet = []
    dh_l_inner_bullet = []

    dh_h_outer_bullet = []
    dh_h_inner_bullet = []

    dh_rr_outer_bullet = []
    dh_rr_inner_bullet = []

    dh_tr_outer_bullet = []
    dh_tr_inner_bullet = []

    pe_outer_bullet = []

    m_am_outer_bullet = []
    m_am_inner_bullet = []
    m_am_rating = []
    

    recom_outer_bullet = []
    recom_inner_bullet = []

    survey_report = SurveyReport.objects.filter(id=int(request.POST['survey_report_id']))
    for img in survey_report[0].fendering_images.all():
        fendering_images_arr.append(str(img.fendering_images))
    
    for bimg in survey_report[0].bulwarks_image.all():
        bulwarks_image_arr.append(str(bimg.bulwarks_image))

    for cimg in survey_report[0].cargo_rails_images.all():
        cargo_rails_images_arr.append(str(cimg.cargo_rails_images))

    for dimg in survey_report[0].deck_fitting_images.all():
        deck_fitting_images_arr.append(str(dimg.deck_fitting_images))

    for gimg in survey_report[0].ground_tackle_images.all():
        ground_tackle_images_arr.append(str(gimg.ground_tackle_images))
    
    for gimg in survey_report[0].hull_comp_images.all():
        hull_comp_images_arr.append(str(gimg.hull_comp_images))

    for dhimg in  survey_report[0].deck_house_image.all():
        deck_house_image_arr.append(str(dhimg.deck_house_image))

    for dhimg in  survey_report[0].pilot_house_image.all():
        pilot_house_image_arr.append(str(dhimg.pilot_house_image))

    for dhimg in  survey_report[0].super_structure_image.all():
        super_structure_image_arr.append(str(dhimg.super_structure_image))

    for dhimg in  survey_report[0].machinary_image.all():
        machinary_image_arr.append(str(dhimg.machinary_image))

    for dhimg in  survey_report[0].safety_equipment_image.all():
        safety_equipment_image_arr.append(str(dhimg.safety_equipment_image))

    data = serializers.serialize("json", survey_report)
    survey_report = survey_report[0]
    
    for bd in survey_report.bulwarks_deck.all():
        bulwarks_deck_name.append(bd.bulwarks_deck_name)
        bulwarks_deck_height.append(bd.bulwarks_deck_height)
        bulwarks_deck_type.append(bd.bulwarks_deck_type)
        bulwarks_deck_material.append(bd.bulwarks_deck_material)
        bulwarks_deck_cap.append(bd.bulwarks_deck_cap)
        bulwarks_deck_cap_dimen.append(bd.bulwarks_deck_cap_dimen)
        bulwarks_deck_stiffeners.append(bd.bulwarks_deck_stiffeners)
        bulwarks_deck_cap_dimen_other.append(bd.bulwarks_deck_cap_dimen_other)
        bulwarks_deck_name_other.append(bd.bulwarks_deck_name_other)
        bulwarks_deck_stiffeners_other.append(bd.bulwarks_deck_stiffeners_other)
        
    for cr in survey_report.cargo_rails.all():
        cargorails_deck_name.append(cr.cargorails_deck_name)
        cargorails_deck_height.append(cr.cargorails_deck_height)
        cargorails_deck_construction.append(cr.cargorails_deck_construction)
        cargorails_deck_cap.append(cr.cargorails_deck_cap)
        cargorails_deck_cap_dimen.append(cr.cargorails_deck_cap_dimen)
        cargorails_deck_stiffeners.append(cr.cargorails_deck_stiffeners)
        cargorails_deck_cap_dimen_other.append(cr.cargorails_deck_cap_dimen_other)
        cargorails_deck_name_other.append(cr.cargorails_deck_name_other)
        cargorails_deck_material.append(cr.cargorails_deck_material)
        
    for df in survey_report.deck_fittings.all():
        df_deck_name_arr.append(df.df_deck_name)
        df_fittings_arr.append(df.df_fittings)
        df_number_arr.append(df.df_number)
        df_size_arr.append(df.df_size)
        df_location_arr.append(df.df_location)
        df_deck_name_other_arr.append(df.df_deck_name_other)
        df_fittings_other_arr.append(df.df_fittings_other)

    for hc in survey_report.hull_comp_tank.all():
        hc_tanktype.append(hc.hc_tank_type)
        hc_tanktypefillings.append(hc.hc_filling_lines)
        hc_tanktypevents.append(hc.hc_vents)

    for hcc in survey_report.hull_comp_capacity.all():
        hc_capacitytype.append(hcc.hc_capacity_type)
        hc_capacitytypefillings.append(hcc.hc_capacity_vol)
        hc_capacitytypevents.append(hcc.hc_capacity_units)

    for bth in survey_report.berthing_compartments.all():
        dh_bc_outer_bullet.append(bth.dh_bc_outer_bullet)
        dh_bc_inner_bullet.append(bth.dh_bc_inner_bullet)

    for bth in survey_report.galley.all():
        dh_g_outer_bullet.append(bth.dh_g_outer_bullet)
        dh_g_inner_bullet.append(bth.dh_g_inner_bullet)

    for bth in survey_report.mess_decks.all():
        dh_md_outer_bullet.append(bth.dh_md_outer_bullet)
        dh_md_inner_bullet.append(bth.dh_md_inner_bullet)

    for bth in survey_report.laundry.all():
        dh_l_outer_bullet.append(bth.dh_l_outer_bullet)
        dh_l_inner_bullet.append(bth.dh_l_inner_bullet)

    for bth in survey_report.hospital.all():
        dh_h_outer_bullet.append(bth.dh_h_outer_bullet)
        dh_h_inner_bullet.append(bth.dh_h_inner_bullet)

    for bth in survey_report.recreation_room.all():
        dh_rr_outer_bullet.append(bth.dh_rr_outer_bullet)
        dh_rr_inner_bullet.append(bth.dh_rr_inner_bullet)

    for bth in survey_report.theater_room.all():
        dh_tr_outer_bullet.append(bth.dh_tr_outer_bullet)
        dh_tr_inner_bullet.append(bth.dh_tr_inner_bullet)

    for bth in survey_report.pilothouse_equipments.all():
        pe_outer_bullet.append(bth.pe_outer_bullet)

    
    for bth in survey_report.auxiliary_machinery.all():
        m_am_outer_bullet.append(bth.m_am_outer_bullet)
        m_am_inner_bullet.append(bth.m_am_inner_bullet)
        m_am_rating.append(bth.m_am_rating)

    for bth in survey_report.recommendations.all():
        recom_outer_bullet.append(bth.recom_outer_bullet)
        recom_inner_bullet.append(bth.recom_inner_bullet)


    return JsonResponse(
        {
            "survey_report": data, 
            'tanktype': hc_tanktype,
            'tanktypefillings': hc_tanktypefillings,
            'tanktypevents': hc_tanktypevents,
            'capacitytype': hc_capacitytype,
            'capacitytypefillings': hc_capacitytypefillings,
            'capacitytypevents': hc_capacitytypevents,
            'bulwarks_deck_name': bulwarks_deck_name,
            'bulwarks_deck_height': bulwarks_deck_height,
            'bulwarks_deck_type': bulwarks_deck_type,
            'bulwarks_deck_material': bulwarks_deck_material,
            'bulwarks_deck_cap': bulwarks_deck_cap,
            'bulwarks_deck_cap_dimen': bulwarks_deck_cap_dimen,
            'bulwarks_deck_stiffeners': bulwarks_deck_stiffeners,
            'bulwarks_deck_cap_dimen_other': bulwarks_deck_cap_dimen_other,
            'bulwarks_deck_name_other': bulwarks_deck_name_other,
            'bulwarks_deck_stiffeners_other': bulwarks_deck_stiffeners_other,
            'df_deck_name':df_deck_name_arr,
            'df_fittings': df_fittings_arr,
            'df_number': df_number_arr,
            'df_size': df_size_arr,
            'df_location': df_location_arr,
            'df_deck_name_other': df_deck_name_other_arr,
            'df_fittings_other': df_fittings_other_arr,
            'cargorails_deck_name': cargorails_deck_name,
            'cargorails_deck_height': cargorails_deck_height,
            'cargorails_deck_construction': cargorails_deck_construction,
            'cargorails_deck_cap': cargorails_deck_cap,
            'cargorails_deck_cap_dimen': cargorails_deck_cap_dimen,
            'cargorails_deck_stiffeners': cargorails_deck_stiffeners,
            'cargorails_deck_cap_dimen_other': cargorails_deck_cap_dimen_other,
            'cargorails_deck_name_other': cargorails_deck_name_other,
            'cargorails_deck_material': cargorails_deck_material,
            'fendering_images_arr': fendering_images_arr, 
            'cargo_rails_images_arr': cargo_rails_images_arr,
            'deck_fitting_images_arr': deck_fitting_images_arr,
            'ground_tackle_images_arr': ground_tackle_images_arr,
            'hull_comp_images_arr': hull_comp_images_arr,
            'bulwarks_image_arr': bulwarks_image_arr,
            'deck_house_image_arr': deck_house_image_arr,
            'pilot_house_image_arr': pilot_house_image_arr,
            'super_structure_image_arr': super_structure_image_arr,
            'machinary_image_arr': machinary_image_arr,
            'safety_equipment_image_arr': safety_equipment_image_arr,
            'dh_bc_outer_bullet': dh_bc_outer_bullet,
            'dh_bc_inner_bullet': dh_bc_inner_bullet,
            'dh_g_outer_bullet': dh_g_outer_bullet,
            'dh_g_inner_bullet': dh_g_inner_bullet,
            'dh_md_outer_bullet': dh_md_outer_bullet,
            'dh_md_inner_bullet': dh_md_inner_bullet,
            'dh_l_outer_bullet': dh_l_outer_bullet,
            'dh_l_inner_bullet': dh_l_inner_bullet,
            'dh_h_outer_bullet': dh_h_outer_bullet,
            'dh_h_inner_bullet': dh_h_inner_bullet,
            'dh_rr_outer_bullet': dh_rr_outer_bullet,
            'dh_rr_inner_bullet': dh_rr_inner_bullet,
            'dh_tr_outer_bullet': dh_tr_outer_bullet,
            'dh_tr_inner_bullet': dh_tr_inner_bullet,
            'pe_outer_bullet': pe_outer_bullet,
            'm_am_outer_bullet': m_am_outer_bullet,
            'm_am_inner_bullet': m_am_inner_bullet,
            'm_am_rating': m_am_rating,
            'recom_outer_bullet': recom_outer_bullet,
            'recom_inner_bullet': recom_inner_bullet
        }
    )



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step1(request):
    survey_report=None
    if request.POST['survey_report_id']!='0':
        survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
        if survey_report:
            survey_report.vessel_description = request.POST['vessel_description']
            survey_report.save()
        else:
            survey_report = SurveyReport.objects.create(
                assignment=AssignVessel.objects.get(pk=int(request.POST['assign_vessel_id'])).assignment,
                assigned_vessel=AssignVessel.objects.get(pk=int(request.POST['assign_vessel_id'])),
                vessel_description=request.POST['vessel_description'],
                gd_extra_note=request.POST['gd_extra_note'],
                created_on=timezone.now(),
            )
    else:
        survey_report = SurveyReport.objects.create(
            assignment=AssignVessel.objects.get(pk=int(request.POST['assign_vessel_id'])).assignment,
            assigned_vessel=AssignVessel.objects.get(pk=int(request.POST['assign_vessel_id'])),
            vessel_description=request.POST['vessel_description'],
            gd_extra_note=request.POST['gd_extra_note'],
            created_on=timezone.now(),
        )
    return JsonResponse({"code": "200","survey_report_id": str(survey_report.id)})


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step1_details(request):
    survey_report = None
    now = datetime.now() + timedelta(hours=1)
    vessel_description = ''
    if request.POST['survey_report_id']:
        survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
        
        request_time = 0
        if request.POST['updated_on'] != '0':
            dt = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            request_time = int(time.mktime(dt.timetuple()))
        if time.mktime(survey_report.updated_on.timetuple() if survey_report.updated_on else now.timetuple()) > request_time:
            vessel_description = survey_report.vessel_description
            return JsonResponse({
                'code':'200',
                'updated_on':str(survey_report.updated_on).replace('T', ' ')[:19] if survey_report.updated_on else str(now).replace('T', ' ')[:19],
                'vessel_description':vessel_description,
                'gd_extra_note':survey_report.gd_extra_note
            })
        else:
            survey_report.vessel_description = request.POST['vessel_description']
            survey_report.gd_extra_note = request.POST['gd_extra_note']
            survey_report.updated_on = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            survey_report.save()
            return JsonResponse({
                'code':'300'
            })
    else:
        survey_report = SurveyReport.objects.create(
            assignment=AssignVessel.objects.get(pk=int(request.POST['assign_vessel_id'])).assignment,
            assigned_vessel=AssignVessel.objects.get(pk=int(request.POST['assign_vessel_id'])),
            vessel_description=request.POST['vessel_description'],
            gd_extra_note=request.POST['gd_extra_note'],
            created_on=timezone.now(),
            updated_on=datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S'),
        )
        return JsonResponse({
            'code':'300',
            "survey_report_id": str(survey_report.id)
        })
        


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step2(request):
    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
    survey_report.port_bow_length_feet = request.POST['port_bow_length_feet']
    survey_report.port_bow_length_inch = request.POST['port_bow_length_inch']
    survey_report.port_stern_length_feet = request.POST['port_stern_length_feet']
    survey_report.port_stern_length_inch = request.POST['port_stern_length_inch']
    survey_report.starboard_bow_length_feet = request.POST['starboard_bow_length_feet']
    survey_report.starboard_bow_length_inch = request.POST['starboard_bow_length_inch']
    survey_report.starboard_stern_length_feet = request.POST['starboard_stern_length_feet']
    survey_report.starboard_stern_length_inch = request.POST['starboard_stern_length_inch']
    survey_report.gd_extra_note = request.POST['gd_extra_note']
    survey_report.save()
    return JsonResponse({"code": "200","survey_report_id": str(survey_report.id)})


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step2_details(request):
    survey_report = None
    
    now = datetime.now() + timedelta(hours=1)
    port_bow_length_feet = ''
    port_bow_length_inch = ''
    port_stern_length_feet = ''
    port_stern_length_inch = ''
    starboard_bow_length_feet = ''
    starboard_bow_length_inch = ''
    starboard_stern_length_feet = ''
    starboard_stern_length_inch = ''
    if request.POST['survey_report_id']:
        survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
        port_bow_length_feet = survey_report.port_bow_length_feet
        port_bow_length_inch = survey_report.port_bow_length_inch
        port_stern_length_feet = survey_report.port_stern_length_feet
        port_stern_length_inch = survey_report.port_stern_length_inch
        starboard_bow_length_feet = survey_report.starboard_bow_length_feet
        starboard_bow_length_inch = survey_report.starboard_bow_length_inch
        starboard_stern_length_feet = survey_report.starboard_stern_length_feet
        starboard_stern_length_inch = survey_report.starboard_stern_length_inch

        request_time = 0
        if request.POST['updated_on'] != '0':
            dt = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            request_time = int(time.mktime(dt.timetuple()))
        if time.mktime(survey_report.updated_on.timetuple() if survey_report.updated_on else now.timetuple()) > request_time:
            data = {
                'port_bow_length_feet':port_bow_length_feet,
                'port_bow_length_inch':port_bow_length_inch,
                'port_stern_length_feet':port_stern_length_feet,
                'port_stern_length_inch':port_stern_length_inch,
                'starboard_bow_length_feet':starboard_bow_length_feet,
                'starboard_bow_length_inch':starboard_bow_length_inch,
                'starboard_stern_length_feet':starboard_stern_length_feet,
                'starboard_stern_length_inch':starboard_stern_length_inch,
                'gd_extra_note':survey_report.gd_extra_note
            }
            return JsonResponse({
                'code':'200',
                'updated_on':str(survey_report.updated_on).replace('T', ' ')[:19] if survey_report.updated_on else str(now).replace('T', ' ')[:19],
                'data':data
            })
        else:
            survey_report.updated_on = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            survey_report.port_bow_length_feet = request.POST['port_bow_length_feet']
            survey_report.port_bow_length_inch = request.POST['port_bow_length_inch']
            survey_report.port_stern_length_feet = request.POST['port_stern_length_feet']
            survey_report.port_stern_length_inch = request.POST['port_stern_length_inch']
            survey_report.starboard_bow_length_feet = request.POST['starboard_bow_length_feet']
            survey_report.starboard_bow_length_inch = request.POST['starboard_bow_length_inch']
            survey_report.starboard_stern_length_feet = request.POST['starboard_stern_length_feet']
            survey_report.starboard_stern_length_inch = request.POST['starboard_stern_length_inch']
            survey_report.gd_extra_note = request.POST['gd_extra_note']
            survey_report.save()
            return JsonResponse({
                'code':'300'
            })



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step3(request):
    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
    survey_report.built_no = request.POST['built_no']
    survey_report.built_details = request.POST['built_details']
    survey_report.official_no = request.POST['official_no']
    survey_report.imo_no = request.POST['imo_no']
    survey_report.previous_name = request.POST['previous_name']
    survey_report.flag = request.POST['flag']
    survey_report.dimentions_length = request.POST['dimentions_length']
    survey_report.dimentions_width =request.POST['dimentions_width'] 
    survey_report.dimentions_height = request.POST['dimentions_height']
    survey_report.overall_length = request.POST['overall_length']
    survey_report.grt = request.POST['grt']
    survey_report.nrt = request.POST['nrt']
    survey_report.git = request.POST['git']
    survey_report.nit = request.POST['nit']
    survey_report.classed_as = request.POST['classed_as']
    survey_report.deck_length = request.POST['deck_length']
    survey_report.deck_width = request.POST['deck_width']
    survey_report.clear_deck_length = request.POST['clear_deck_length']
    survey_report.clear_deck_width = request.POST['clear_deck_width']
    survey_report.deck_cargo_rating = request.POST['deck_cargo_rating']
    survey_report.engine_description = request.POST['engine_description']
    survey_report.horsepower_min = request.POST['horsepower_min']
    survey_report.horsepower_max = request.POST['horsepower_max']
    survey_report.drive = request.POST['drive']
    survey_report.gd_extra_note = request.POST['gd_extra_note']
    survey_report.save()
    return JsonResponse({"code": "200","survey_report_id": str(survey_report.id)})


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step3_details(request):
    survey_report = None
    now = datetime.now() + timedelta(hours=1)
    
    built_no = ''
    built_details = ''
    official_no = ''
    imo_no = ''
    previous_name = ''
    flag = ''
    dimentions_length = ''
    dimentions_width = ''
    dimentions_height = ''
    overall_length = ''
    grt = ''
    nrt = ''
    git = ''
    nit = ''
    classed_as = ''
    deck_length = ''
    deck_width = ''
    clear_deck_length = ''
    clear_deck_width = ''
    deck_cargo_rating = ''
    engine_description = ''
    horsepower_min = ''
    horsepower_max = ''
    drive = ''
    if request.POST['survey_report_id']:
        survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))

        built_no = survey_report.built_no
        built_details = survey_report.built_details
        official_no = survey_report.official_no
        imo_no = survey_report.imo_no
        previous_name = survey_report.previous_name
        flag = survey_report.flag
        dimentions_length = survey_report.dimentions_length
        dimentions_width = survey_report.dimentions_width
        dimentions_height = survey_report.dimentions_height
        overall_length = survey_report.overall_length
        grt = survey_report.grt
        nrt = survey_report.nrt
        git = survey_report.git
        nit = survey_report.nit
        classed_as = survey_report.classed_as
        deck_length = survey_report.deck_length
        deck_width = survey_report.deck_width
        clear_deck_length = survey_report.clear_deck_length
        clear_deck_width = survey_report.clear_deck_width
        deck_cargo_rating = survey_report.deck_cargo_rating
        engine_description = survey_report.engine_description
        horsepower_min = survey_report.horsepower_min
        horsepower_max = survey_report.horsepower_max
        drive = survey_report.drive

        request_time = 0
        if request.POST['updated_on'] != '0':
            dt = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            request_time = int(time.mktime(dt.timetuple()))
        if time.mktime(survey_report.updated_on.timetuple() if survey_report.updated_on else now.timetuple()) > request_time:
            data = {
                'built_no':built_no,
                'built_details':built_details,
                'official_no':official_no,
                'previous_name':previous_name,
                'imo_no':imo_no,
                'flag':flag,
                'dimentions_length':dimentions_length,
                'dimentions_width':dimentions_width,
                'dimentions_height':dimentions_height,
                'overall_length':overall_length,
                'grt':grt,
                'nrt':nrt,
                'git':git,
                'nit':nit,
                'classed_as':classed_as,
                'deck_length':deck_length,
                'deck_width':deck_width,
                'clear_deck_length':clear_deck_length,
                'clear_deck_width':clear_deck_width,
                'deck_cargo_rating':deck_cargo_rating,
                'engine_description':engine_description,
                'horsepower_min':horsepower_min,      
                'horsepower_max':horsepower_max,
                'drive':drive,
                'gd_extra_note':survey_report.gd_extra_note
            }
            return JsonResponse({
                'code':'200',
                'updated_on':str(survey_report.updated_on).replace('T', ' ')[:19] if survey_report.updated_on else str(now).replace('T', ' ')[:19],
                'data':data
            })
        else:
            survey_report.updated_on = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')

            survey_report.built_no = request.POST['built_no']
            survey_report.built_details = request.POST['built_details']
            survey_report.official_no = request.POST['official_no']
            survey_report.imo_no = request.POST['imo_no']
            survey_report.previous_name = request.POST['previous_name']
            survey_report.flag = request.POST['flag']
            survey_report.dimentions_length = request.POST['dimentions_length']
            survey_report.dimentions_width =request.POST['dimentions_width'] 
            survey_report.dimentions_height = request.POST['dimentions_height']
            survey_report.overall_length = request.POST['overall_length']
            survey_report.grt = request.POST['grt']
            survey_report.nrt = request.POST['nrt']
            survey_report.git = request.POST['git']
            survey_report.nit = request.POST['nit']
            survey_report.classed_as = request.POST['classed_as']
            survey_report.deck_length = request.POST['deck_length']
            survey_report.deck_width = request.POST['deck_width']
            survey_report.clear_deck_length = request.POST['clear_deck_length']
            survey_report.clear_deck_width = request.POST['clear_deck_width']
            survey_report.deck_cargo_rating = request.POST['deck_cargo_rating']
            survey_report.engine_description = request.POST['engine_description']
            survey_report.horsepower_min = request.POST['horsepower_min']
            survey_report.horsepower_max = request.POST['horsepower_max']
            survey_report.drive = request.POST['drive']
            survey_report.gd_extra_note = request.POST['gd_extra_note']
            survey_report.save()
            return JsonResponse({
                'code':'300'
            })


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step4(request):
    fhf_locations = ''
    for fhf_location in request.POST.getlist('fhf_location1'):
        fhf_locations += fhf_location+','
    rf_locations = ''
    for rf_location in request.POST.getlist('rf_location2'):
        rf_locations += rf_location+','
    tf_locations = ''
    for tf_location in request.POST.getlist('tf_location3'):
        tf_locations += tf_location+','

    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
    survey_report.fhf_courses = request.POST['fhf_courses']
    survey_report.fhf_length = request.POST['fhf_length']
    survey_report.fhf_width = request.POST['fhf_width']
    survey_report.fhf_construction1 = request.POST['fhf_construction1']
    survey_report.fhf_location1 = fhf_locations[:-1]
    survey_report.fhf_construction1_other = request.POST.get('fhf_construction1_other', '')
    survey_report.rf_courses = request.POST['rf_courses']
    survey_report.rf_length = request.POST['rf_length']
    survey_report.rf_number1 =request.POST['rf_number1']
    survey_report.rf_construction2 = request.POST['rf_construction2']
    survey_report.fendering_condition_rating = request.POST['fendering_condition_rating']
    survey_report.fendering_condition = request.POST['fendering_condition']
    survey_report.rf_location2 = rf_locations[:-1]
    survey_report.rf_construction2_other = request.POST.get('rf_construction2_other', '')
    survey_report.tf_courses = request.POST['tf_courses']
    survey_report.tf_size1 = request.POST['tf_size1']
    survey_report.tf_mounting1 =request.POST['tf_mounting1']
    survey_report.tf_location3 = tf_locations[:-1]
    survey_report.fendering_additional_commentary =request.POST['fendering_additional_commentary']
    survey_report.gd_extra_note = request.POST['gd_extra_note']
    survey_report.save()
    return JsonResponse({"code": "200","survey_report_id": str(survey_report.id)})


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step4_details(request):
    survey_report = None
    now = datetime.now() + timedelta(hours=1)
    fhf_courses = ''
    fhf_length = ''
    fhf_width = ''
    fhf_construction1 = ''
    fhf_location1 = ''
    fhf_construction1_other = ''
    rf_courses = ''
    rf_length = ''
    rf_number1 = ''
    rf_construction2 = ''
    fendering_condition_rating = ''
    fendering_condition = ''
    rf_location2 = ''
    rf_construction2_other = ''
    tf_courses = ''
    tf_size1 = ''
    tf_mounting1 = ''
    tf_location3 = ''
    fendering_additional_commentary = ''
    fendering_images_arr = []
    if request.POST['survey_report_id']:
        survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
        fhf_courses = survey_report.fhf_courses
        fhf_length = survey_report.fhf_length
        fhf_width = survey_report.fhf_width
        fhf_construction1 = survey_report.fhf_construction1
        fhf_location1 = survey_report.fhf_location1.split(',')
        fhf_construction1_other = survey_report.fhf_construction1_other
        rf_courses = survey_report.rf_courses
        rf_length = survey_report.rf_length
        rf_number1 = survey_report.rf_number1
        rf_construction2 = survey_report.rf_construction2
        fendering_condition_rating = survey_report.fendering_condition_rating
        fendering_condition = survey_report.fendering_condition
        rf_location2 = survey_report.rf_location2.split(',')
        rf_construction2_other = survey_report.rf_construction2_other
        tf_courses = survey_report.tf_courses
        tf_size1 = survey_report.tf_size1
        tf_mounting1 = survey_report.tf_mounting1
        tf_location3 = survey_report.tf_location3.split(',')
        fendering_additional_commentary = survey_report.fendering_additional_commentary

        for img in survey_report.fendering_images.all():
            fendering_images_arr.append(str(GlobalConfiguration.get_as_base64(str(img.fendering_images)))[2:-1])
        
        request_time = 0
        if request.POST['updated_on'] != '0':
            dt = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            request_time = int(time.mktime(dt.timetuple()))
        if time.mktime(survey_report.updated_on.timetuple() if survey_report.updated_on else now.timetuple()) > request_time:
            data = {
                'fhf_courses':fhf_courses,
                'fhf_length':fhf_length,
                'fhf_width':fhf_width,
                'fhf_construction1':fhf_construction1,
                'fhf_location1':fhf_location1,
                'fhf_construction1_other':fhf_construction1_other,
                'rf_courses':rf_courses,
                'rf_length':rf_length,
                'rf_number1':rf_number1,
                'rf_construction2':rf_construction2,
                'fendering_condition_rating':fendering_condition_rating,
                'fendering_condition':fendering_condition,
                'rf_location2':rf_location2,
                'rf_construction2_other':rf_construction2_other,
                'tf_courses':tf_courses,
                'tf_size1':tf_size1,
                'tf_mounting1':tf_mounting1,
                'tf_location3':tf_location3,
                'fendering_additional_commentary':fendering_additional_commentary,
                'gd_extra_note':survey_report.gd_extra_note
            }
            return JsonResponse({
                'code':'200',
                'updated_on':str(survey_report.updated_on).replace('T', ' ')[:19] if survey_report.updated_on else str(now).replace('T', ' ')[:19],
                'data':data,
                'fendering_images_arr':fendering_images_arr
                })
        else:
            survey_report.updated_on = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            fhf_locations = ''
            for fhf_location in request.POST.getlist('fhf_location1'):
                fhf_locations += fhf_location+','
            rf_locations = ''
            for rf_location in request.POST.getlist('rf_location2'):
                rf_locations += rf_location+','
            tf_locations = ''
            for tf_location in request.POST.getlist('tf_location3'):
                tf_locations += tf_location+','

            survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
            survey_report.fhf_courses = request.POST['fhf_courses']
            survey_report.fhf_length = request.POST['fhf_length']
            survey_report.fhf_width = request.POST['fhf_width']
            survey_report.fhf_construction1 = request.POST['fhf_construction1']
            survey_report.fhf_location1 = fhf_locations[:-1]
            survey_report.fhf_construction1_other = request.POST.get('fhf_construction1_other', '')
            survey_report.rf_courses = request.POST['rf_courses']
            survey_report.rf_length = request.POST['rf_length']
            survey_report.rf_number1 =request.POST['rf_number1']
            survey_report.rf_construction2 = request.POST['rf_construction2']
            survey_report.fendering_condition_rating = request.POST['fendering_condition_rating']
            survey_report.fendering_condition = request.POST['fendering_condition']
            survey_report.rf_location2 = rf_locations[:-1]
            survey_report.rf_construction2_other = request.POST.get('rf_construction2_other', '')
            survey_report.tf_courses = request.POST['tf_courses']
            survey_report.tf_size1 = request.POST['tf_size1']
            survey_report.tf_mounting1 =request.POST['tf_mounting1']
            survey_report.tf_location3 = tf_locations[:-1]
            survey_report.fendering_additional_commentary =request.POST['fendering_additional_commentary']
            survey_report.gd_extra_note = request.POST['gd_extra_note']

            img_data = request.POST.get('img_data').replace("[","").replace("]","")
            img_data_arr = img_data.split(",")
            survey_report.fendering_images.all().delete()
            for image_data in img_data_arr:
                url = GlobalConfiguration.api_b64_aws_s3_image_post("fendering_images/",image_data)
                fnd_images = FenderingImages.objects.create(
                    fendering_images=url
                )
                survey_report.fendering_images.add(fnd_images)

            survey_report.save()
            return JsonResponse({
                'code':'300'
            })


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step4_image(request):
    file_name = "fendering_images/"+str(uuid.uuid4())+".jpg"
    image_data = request.POST.get('image_data')
    
    #image_data += "==" * ((4 - len(image_data) % 4) % 4)

    image_data = image_data.replace(" ","+")
    session = boto3.session.Session(aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_KEY)
    s3 = session.resource('s3')
    s3.Bucket("dls2018").put_object(Key=file_name, Body=base64.b64decode(image_data), ContentType='image/jpeg', ACL='public-read')
    url = settings.AWS_S3_URL+file_name
    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
    fnd_images = FenderingImages.objects.create(
        fendering_images=str(url)
    )
    survey_report.fendering_images.add(fnd_images)
    return JsonResponse({"code": url})



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step5_image(request):
    file_name = "bulwarks_images/"+str(uuid.uuid4())+".jpg"
    image_data = request.POST.get('image_data')
    
    #image_data += "==" * ((4 - len(image_data) % 4) % 4)
    image_data = image_data.replace(" ","+")

    session = boto3.session.Session(aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_KEY)
    s3 = session.resource('s3')
    s3.Bucket("dls2018").put_object(Key=file_name, Body=base64.b64decode(image_data), ContentType='image/jpeg', ACL='public-read')
    url = settings.AWS_S3_URL+file_name

    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
    fnd_images = BulwarksImage.objects.create(
        bulwarks_image=str(url)
    )
    survey_report.bulwarks_image.add(fnd_images)
    return JsonResponse({"code": str(url)})



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step5(request):
    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))

    survey_report.bulwarks_deck.all().delete()
    
    bulwarks_deck_names = request.POST.get('bulwarks_deck_name').split(',')
    bulwarks_deck_name_others = request.POST.get('bulwarks_deck_name_other').split(',') if request.POST.get('bulwarks_deck_name_other') else ''
    bulwarks_deck_heights = request.POST.get('bulwarks_deck_height').split(',')
    bulwarks_deck_types = request.POST.get('bulwarks_deck_type').split(',')
    bulwarks_deck_materials = request.POST.get('bulwarks_deck_material').split(',')
    bulwarks_deck_caps = request.POST.get('bulwarks_deck_cap').split(',')
    bulwarks_deck_cap_dimens = request.POST.get('bulwarks_deck_cap_dimen').split(',')
    bulwarks_deck_cap_dimen_others = request.POST.get('bulwarks_deck_cap_dimen_other').split(',') if request.POST.get('bulwarks_deck_cap_dimen_other') else ''
    bulwarks_deck_stiffenerss = request.POST.get('bulwarks_deck_stiffeners').split(',')
    bulwarks_deck_stiffeners_others = request.POST.get('bulwarks_deck_stiffeners_other').split(',') if request.POST.get('bulwarks_deck_stiffeners_other') else ''
    


    for index, bulwarks in enumerate(bulwarks_deck_names):
        bulwarks_deck = BulwarksDeck.objects.create(
            bulwarks_deck_name=bulwarks_deck_names[index],
            bulwarks_deck_name_other=bulwarks_deck_name_others[index] if bulwarks_deck_name_others else '',
            bulwarks_deck_height=bulwarks_deck_heights[index],
            bulwarks_deck_type=bulwarks_deck_types[index],
            bulwarks_deck_material=bulwarks_deck_materials[index],
            bulwarks_deck_cap=bulwarks_deck_caps[index],
            bulwarks_deck_cap_dimen=bulwarks_deck_cap_dimens[index],
            bulwarks_deck_cap_dimen_other=bulwarks_deck_cap_dimen_others[index] if bulwarks_deck_cap_dimen_others else '',
            bulwarks_deck_stiffeners=bulwarks_deck_stiffenerss[index],
            bulwarks_deck_stiffeners_other=bulwarks_deck_stiffeners_others[index] if bulwarks_deck_stiffeners_others else '',
        )
        survey_report.bulwarks_deck.add(bulwarks_deck)


    survey_report.bulwarks_description = request.POST['bulwarks_description']
    survey_report.bulwarks_condition_rating = request.POST['bulwarks_condition_rating']
    survey_report.bulwarks_condition = request.POST['bulwarks_condition']
    survey_report.gd_extra_note = request.POST['gd_extra_note']
    survey_report.save()
    return JsonResponse({"code": "200","survey_report_id": str(survey_report.id)})



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step5_details(request):
    survey_report = None
    now = datetime.now() + timedelta(hours=1)
    bulwarks_description = ''
    bulwarks_condition_rating = ''
    bulwarks_condition = ''
    bulwarks_image_arr = []
    bulwarks_deck_name = []
    bulwarks_deck_height = []
    bulwarks_deck_type = []
    bulwarks_deck_material = []
    bulwarks_deck_cap = []
    bulwarks_deck_cap_dimen = []
    bulwarks_deck_stiffeners = []
    bulwarks_deck_cap_dimen_other = []
    bulwarks_deck_name_other = []
    bulwarks_deck_stiffeners_other = []

    if request.POST['survey_report_id']:
        survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
        
        request_time = 0
        if request.POST['updated_on'] != '0':
            dt = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            request_time = int(time.mktime(dt.timetuple()))
        if time.mktime(survey_report.updated_on.timetuple() if survey_report.updated_on else now.timetuple()) > request_time:

            bulwarks_description = survey_report.bulwarks_description
            bulwarks_condition_rating = survey_report.bulwarks_condition_rating
            bulwarks_condition = survey_report.bulwarks_condition

            for bimg in survey_report.bulwarks_image.all():
                bulwarks_image_arr.append(str(GlobalConfiguration.get_as_base64(str(bimg.bulwarks_image)))[2:-1])

            for bd in survey_report.bulwarks_deck.all():
                bulwarks_deck_name.append(bd.bulwarks_deck_name)
                bulwarks_deck_height.append(bd.bulwarks_deck_height)
                bulwarks_deck_type.append(bd.bulwarks_deck_type)
                bulwarks_deck_material.append(bd.bulwarks_deck_material)
                bulwarks_deck_cap.append(bd.bulwarks_deck_cap)
                bulwarks_deck_cap_dimen.append(bd.bulwarks_deck_cap_dimen)
                bulwarks_deck_stiffeners.append(bd.bulwarks_deck_stiffeners)
                bulwarks_deck_cap_dimen_other.append(bd.bulwarks_deck_cap_dimen_other)
                bulwarks_deck_name_other.append(bd.bulwarks_deck_name_other)
                bulwarks_deck_stiffeners_other.append(bd.bulwarks_deck_stiffeners_other)

            return JsonResponse({
                'code':'200',
                'updated_on':str(survey_report.updated_on).replace('T', ' ')[:19] if survey_report.updated_on else str(now).replace('T', ' ')[:19],
                'bulwarks_description':bulwarks_description,
                'bulwarks_condition_rating':bulwarks_condition_rating,
                'bulwarks_condition':bulwarks_condition,
                'bulwarks_image_arr':bulwarks_image_arr,
                'bulwarks_deck_name': bulwarks_deck_name,
                'bulwarks_deck_height': bulwarks_deck_height,
                'bulwarks_deck_type': bulwarks_deck_type,
                'bulwarks_deck_material': bulwarks_deck_material,
                'bulwarks_deck_cap': bulwarks_deck_cap,
                'bulwarks_deck_cap_dimen': bulwarks_deck_cap_dimen,
                'bulwarks_deck_stiffeners': bulwarks_deck_stiffeners,
                'bulwarks_deck_cap_dimen_other': bulwarks_deck_cap_dimen_other,
                'bulwarks_deck_name_other': bulwarks_deck_name_other,
                'bulwarks_deck_stiffeners_other': bulwarks_deck_stiffeners_other,
                'gd_extra_note':survey_report.gd_extra_note
            })
        else:
                    
            survey_report.bulwarks_deck.all().delete()
            
            bulwarks_deck_names = request.POST.get('bulwarks_deck_name').split(',')
            bulwarks_deck_name_others = request.POST.get('bulwarks_deck_name_other').split(',') if request.POST.get('bulwarks_deck_name_other') else ''
            bulwarks_deck_heights = request.POST.get('bulwarks_deck_height').split(',')
            bulwarks_deck_types = request.POST.get('bulwarks_deck_type').split(',')
            bulwarks_deck_materials = request.POST.get('bulwarks_deck_material').split(',')
            bulwarks_deck_caps = request.POST.get('bulwarks_deck_cap').split(',')
            bulwarks_deck_cap_dimens = request.POST.get('bulwarks_deck_cap_dimen').split(',')
            bulwarks_deck_cap_dimen_others = request.POST.get('bulwarks_deck_cap_dimen_other').split(',') if request.POST.get('bulwarks_deck_cap_dimen_other') else ''
            bulwarks_deck_stiffenerss = request.POST.get('bulwarks_deck_stiffeners').split(',')
            bulwarks_deck_stiffeners_others = request.POST.get('bulwarks_deck_stiffeners_other').split(',') if request.POST.get('bulwarks_deck_stiffeners_other') else ''
            

            for index, bulwarks in enumerate(bulwarks_deck_names):
                bulwarks_deck = BulwarksDeck.objects.create(
                    bulwarks_deck_name=bulwarks_deck_names[index],
                    bulwarks_deck_name_other=bulwarks_deck_name_others[index] if bulwarks_deck_name_others else '',
                    bulwarks_deck_height=bulwarks_deck_heights[index],
                    bulwarks_deck_type=bulwarks_deck_types[index],
                    bulwarks_deck_material=bulwarks_deck_materials[index],
                    bulwarks_deck_cap=bulwarks_deck_caps[index],
                    bulwarks_deck_cap_dimen=bulwarks_deck_cap_dimens[index],
                    bulwarks_deck_cap_dimen_other=bulwarks_deck_cap_dimen_others[index] if bulwarks_deck_cap_dimen_others else '',
                    bulwarks_deck_stiffeners=bulwarks_deck_stiffenerss[index],
                    bulwarks_deck_stiffeners_other=bulwarks_deck_stiffeners_others[index] if bulwarks_deck_stiffeners_others else '',
                )
                survey_report.bulwarks_deck.add(bulwarks_deck)

            survey_report.bulwarks_description = request.POST['bulwarks_description']
            survey_report.bulwarks_condition_rating = request.POST['bulwarks_condition_rating']
            survey_report.bulwarks_condition = request.POST['bulwarks_condition']
            survey_report.gd_extra_note = request.POST['gd_extra_note']

            img_data = request.POST.get('img_data').replace("[","").replace("]","")
            img_data_arr = img_data.split(",")
            survey_report.bulwarks_image.all().delete()
            for image_data in img_data_arr:
                url = GlobalConfiguration.api_b64_aws_s3_image_post("bulwarks_images/",image_data)
                fnd_images = BulwarksImage.objects.create(
                    bulwarks_image=url
                )
                survey_report.bulwarks_image.add(fnd_images)

            survey_report.save()

            return JsonResponse({
                'code':'300'
            })


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step6_image(request):
    file_name = "cargo_rails_image/"+str(uuid.uuid4())+".jpg"
    image_data = request.POST.get('image_data')
    
    #image_data += "==" * ((4 - len(image_data) % 4) % 4)
    image_data = image_data.replace(" ","+")
    session = boto3.session.Session(aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_KEY)
    s3 = session.resource('s3')
    s3.Bucket("dls2018").put_object(Key=file_name, Body=base64.b64decode(image_data), ContentType='image/jpeg', ACL='public-read')
    url = settings.AWS_S3_URL+file_name
    
    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
    fnd_images = CargoRailsImage.objects.create(
        cargo_rails_images=str(url)
    )
    survey_report.cargo_rails_images.add(fnd_images)
    return JsonResponse({"code": str(url)})



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step6(request):
    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))

    survey_report.cargo_rails.all().delete()
    
    cargorails_deck_names = request.POST.get('cargorails_deck_name').split(',')
    cargorails_deck_name_others = request.POST.get('cargorails_deck_name_other').split(',') if request.POST.get('cargorails_deck_name_other') else ''
    cargorails_deck_heights = request.POST.get('cargorails_deck_height').split(',')
    cargorails_deck_materials = request.POST.get('cargorails_deck_material').split(',')
    cargorails_deck_constructions = request.POST.get('cargorails_deck_construction').split(',')        
    cargorails_deck_caps = request.POST.get('cargorails_deck_cap').split(',')
    cargorails_deck_cap_dimens = request.POST.get('cargorails_deck_cap_dimen').split(',')
    cargorails_deck_cap_dimen_others = request.POST.get('cargorails_deck_cap_dimen_other').split(',') if request.POST.get('cargorails_deck_cap_dimen_other') else ''
    cargorails_deck_stiffenerss = request.POST.get('cargorails_deck_stiffeners').split(',')

    for index, cargorails in enumerate(cargorails_deck_names):
        cargo_rails = CargoRails.objects.create(
            cargorails_deck_name=cargorails_deck_names[index],
            cargorails_deck_name_other=cargorails_deck_name_others[index] if cargorails_deck_name_others else '',
            cargorails_deck_height=cargorails_deck_heights[index],
            cargorails_deck_material=cargorails_deck_materials[index],
            cargorails_deck_construction=cargorails_deck_constructions[index],                
            cargorails_deck_cap=cargorails_deck_caps[index],
            cargorails_deck_cap_dimen=cargorails_deck_cap_dimens[index],
            cargorails_deck_cap_dimen_other=cargorails_deck_cap_dimen_others[index] if cargorails_deck_cap_dimen_others else '',
            cargorails_deck_stiffeners=cargorails_deck_stiffenerss[index],
        )
        survey_report.cargo_rails.add(cargo_rails)

    survey_report.cargorails_description = request.POST['cargorails_description']
    survey_report.cargorails_condition_rating = request.POST['cargorails_condition_rating']
    survey_report.cargorails_condition = request.POST['cargorails_condition']
    survey_report.gd_extra_note = request.POST['gd_extra_note']
    survey_report.save()
    return JsonResponse({"code": "200","survey_report_id": str(survey_report.id)})



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step6_details(request):
    survey_report = None
    now = datetime.now() + timedelta(hours=1)
    cargorails_description = ''
    cargorails_condition_rating = ''
    cargorails_condition = ''
    cargo_rails_images_arr = []
    cargorails_deck_name = []
    cargorails_deck_height = []
    cargorails_deck_construction = []
    cargorails_deck_cap = []
    cargorails_deck_cap_dimen = []
    cargorails_deck_stiffeners = []
    cargorails_deck_cap_dimen_other = []
    cargorails_deck_name_other = []
    cargorails_deck_material = []
    if request.POST['survey_report_id']:
        survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))

        request_time = 0
        if request.POST['updated_on'] != '0':
            dt = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            request_time = int(time.mktime(dt.timetuple()))
        if time.mktime(survey_report.updated_on.timetuple() if survey_report.updated_on else now.timetuple()) > request_time:

            cargorails_description = survey_report.cargorails_description
            cargorails_condition_rating = survey_report.cargorails_condition_rating
            cargorails_condition = survey_report.cargorails_condition

            for cimg in survey_report.cargo_rails_images.all():
                cargo_rails_images_arr.append(str(GlobalConfiguration.get_as_base64(str(cimg.cargo_rails_images)))[2:-1])

            for cr in survey_report.cargo_rails.all():
                cargorails_deck_name.append(cr.cargorails_deck_name)
                cargorails_deck_height.append(cr.cargorails_deck_height)
                cargorails_deck_construction.append(cr.cargorails_deck_construction)
                cargorails_deck_cap.append(cr.cargorails_deck_cap)
                cargorails_deck_cap_dimen.append(cr.cargorails_deck_cap_dimen)
                cargorails_deck_stiffeners.append(cr.cargorails_deck_stiffeners)
                cargorails_deck_cap_dimen_other.append(cr.cargorails_deck_cap_dimen_other)
                cargorails_deck_name_other.append(cr.cargorails_deck_name_other)
                cargorails_deck_material.append(cr.cargorails_deck_material)

            return JsonResponse({
                'code':'200',
                'updated_on':str(survey_report.updated_on).replace('T', ' ')[:19] if survey_report.updated_on else str(now).replace('T', ' ')[:19],
                'cargorails_description':cargorails_description,
                'cargorails_condition_rating':cargorails_condition_rating,
                'cargorails_condition':cargorails_condition,
                'cargo_rails_images_arr':cargo_rails_images_arr,
                'cargorails_deck_name':cargorails_deck_name,
                'cargorails_deck_height':cargorails_deck_height,
                'cargorails_deck_construction':cargorails_deck_construction,
                'cargorails_deck_cap':cargorails_deck_cap,
                'cargorails_deck_cap_dimen':cargorails_deck_cap_dimen,
                'cargorails_deck_stiffeners':cargorails_deck_stiffeners,
                'cargorails_deck_cap_dimen_other':cargorails_deck_cap_dimen_other,
                'cargorails_deck_name_other':cargorails_deck_name_other,
                'cargorails_deck_material':cargorails_deck_material,
                'gd_extra_note':survey_report.gd_extra_note
            })
        else:
                    
            survey_report.cargo_rails.all().delete()
            
            cargorails_deck_names = request.POST.get('cargorails_deck_name').split(',')
            cargorails_deck_name_others = request.POST.get('cargorails_deck_name_other').split(',') if request.POST.get('cargorails_deck_name_other') else ''
            cargorails_deck_heights = request.POST.get('cargorails_deck_height').split(',')
            cargorails_deck_materials = request.POST.get('cargorails_deck_material').split(',')
            cargorails_deck_constructions = request.POST.get('cargorails_deck_construction').split(',')        
            cargorails_deck_caps = request.POST.get('cargorails_deck_cap').split(',')
            cargorails_deck_cap_dimens = request.POST.get('cargorails_deck_cap_dimen').split(',')
            cargorails_deck_cap_dimen_others = request.POST.get('cargorails_deck_cap_dimen_other').split(',') if request.POST.get('cargorails_deck_cap_dimen_other') else ''
            cargorails_deck_stiffenerss = request.POST.get('cargorails_deck_stiffeners').split(',')

            for index, cargorails in enumerate(cargorails_deck_names):
                cargo_rails = CargoRails.objects.create(
                    cargorails_deck_name=cargorails_deck_names[index],
                    cargorails_deck_name_other=cargorails_deck_name_others[index] if cargorails_deck_name_others else '',
                    cargorails_deck_height=cargorails_deck_heights[index],
                    cargorails_deck_material=cargorails_deck_materials[index],
                    cargorails_deck_construction=cargorails_deck_constructions[index],                
                    cargorails_deck_cap=cargorails_deck_caps[index],
                    cargorails_deck_cap_dimen=cargorails_deck_cap_dimens[index],
                    cargorails_deck_cap_dimen_other=cargorails_deck_cap_dimen_others[index] if cargorails_deck_cap_dimen_others else '',
                    cargorails_deck_stiffeners=cargorails_deck_stiffenerss[index],
                )
                survey_report.cargo_rails.add(cargo_rails)

            survey_report.cargorails_description = request.POST['cargorails_description']
            survey_report.cargorails_condition_rating = request.POST['cargorails_condition_rating']
            survey_report.cargorails_condition = request.POST['cargorails_condition']
            survey_report.gd_extra_note = request.POST['gd_extra_note']


            img_data = request.POST.get('img_data').replace("[","").replace("]","")
            img_data_arr = img_data.split(",")
            survey_report.cargo_rails_images.all().delete()
            for image_data in img_data_arr:
                url = GlobalConfiguration.api_b64_aws_s3_image_post("cargo_rails_image/",image_data)
                fnd_images = CargoRailsImage.objects.create(
                    cargo_rails_images=url
                )
                survey_report.cargo_rails_images.add(fnd_images)

            survey_report.save()

            return JsonResponse({
                'code':'300'
            })


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step7_image(request):
    file_name = "deck_fitting_images/"+str(uuid.uuid4())+".jpg"
    image_data = request.POST.get('image_data')
    
    #image_data += "==" * ((4 - len(image_data) % 4) % 4)
    image_data = image_data.replace(" ","+")

    session = boto3.session.Session(aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_KEY)
    s3 = session.resource('s3')
    s3.Bucket("dls2018").put_object(Key=file_name, Body=base64.b64decode(image_data), ContentType='image/jpeg', ACL='public-read')
    url = settings.AWS_S3_URL+file_name

    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
    fnd_images = DeckFittingsImage.objects.create(
        deck_fitting_images=str(url)
    )
    survey_report.deck_fitting_images.add(fnd_images)
    return JsonResponse({"code": str(url)})



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step7(request):
    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))

    survey_report.deck_fittings.all().delete()
    
    df_deck_names = request.POST.get('df_deck_name').split(',') if request.POST.get('df_deck_name') else ''
    df_deck_name_others = request.POST.get('df_deck_name_other').split(',') if request.POST.get('df_deck_name_other') else ''
    df_fittingss = request.POST.get('df_fittings').split(',') if request.POST.get('df_fittings') else ''
    df_fittings_others = request.POST.get('df_fittings_other').split(',') if request.POST.get('df_fittings_other') else ''
    df_numbers = request.POST.get('df_number').split(',') if request.POST.get('df_number') else ''
    df_sizes = request.POST.get('df_size').split(',') if request.POST.get('df_size') else ''
    df_locations = request.POST.get('df_location').split(',') if request.POST.get('df_location') else ''
    

    for index, df in enumerate(df_deck_names):
        deck_fittings = DeckFittings.objects.create(
            df_deck_name=df_deck_names[index] if df_deck_names else '',
            df_deck_name_other=df_deck_name_others[index] if df_deck_name_others else '',
            df_fittings=df_fittingss[index] if df_fittingss else '',
            df_fittings_other=df_fittings_others[index] if df_fittings_others else '',
            df_number=df_numbers[index] if df_numbers else '',
            df_size=df_sizes[index] if df_sizes else '',
            df_location=df_locations[index] if df_locations else '',
        )
        survey_report.deck_fittings.add(deck_fittings)


    survey_report.deck_fittings_description = request.POST['deck_fittings_description']
    survey_report.deck_fittings_condition_rating = request.POST['deck_fittings_condition_rating']
    survey_report.deck_fittings_condition = request.POST['deck_fittings_condition']
    survey_report.gd_extra_note = request.POST['gd_extra_note']
    survey_report.save()
    return JsonResponse({"code": "200","survey_report_id": str(survey_report.id)})



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step7_details(request):
    survey_report = None
    now = datetime.now() + timedelta(hours=1)
    deck_fittings_description = ''
    deck_fittings_condition_rating = ''
    deck_fittings_condition = ''
    deck_fitting_images_arr = []
    df_deck_name_arr = []
    df_fittings_arr = []
    df_number_arr = []
    df_size_arr = []
    df_location_arr = []
    df_deck_name_other_arr = []
    df_fittings_other_arr = []
    if request.POST['survey_report_id']:
        survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))

        request_time = 0
        if request.POST['updated_on'] != '0':
            dt = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            request_time = int(time.mktime(dt.timetuple()))
        if time.mktime(survey_report.updated_on.timetuple() if survey_report.updated_on else now.timetuple()) > request_time:

            deck_fittings_description = survey_report.deck_fittings_description
            deck_fittings_condition_rating = survey_report.deck_fittings_condition_rating
            deck_fittings_condition = survey_report.deck_fittings_condition

            for dimg in survey_report.deck_fitting_images.all():
                deck_fitting_images_arr.append(str(GlobalConfiguration.get_as_base64(str(dimg.deck_fitting_images)))[2:-1])

            for df in survey_report.deck_fittings.all():
                df_deck_name_arr.append(df.df_deck_name)
                df_fittings_arr.append(df.df_fittings)
                df_number_arr.append(df.df_number)
                df_size_arr.append(df.df_size)
                df_location_arr.append(df.df_location)
                df_deck_name_other_arr.append(df.df_deck_name_other)
                df_fittings_other_arr.append(df.df_fittings_other)

            return JsonResponse({
                'code':'200',
                'updated_on':str(survey_report.updated_on).replace('T', ' ')[:19] if survey_report.updated_on else str(now).replace('T', ' ')[:19],
                'deck_fittings_description':deck_fittings_description,
                'deck_fittings_condition_rating':deck_fittings_condition_rating,
                'deck_fittings_condition':deck_fittings_condition,
                'deck_fitting_images_arr':deck_fitting_images_arr,
                'df_deck_name_arr':df_deck_name_arr,
                'df_fittings_arr':df_fittings_arr,
                'df_number_arr':df_number_arr,
                'df_size_arr':df_size_arr,
                'df_location_arr':df_location_arr,
                'df_deck_name_other_arr':df_deck_name_other_arr,
                'df_fittings_other_arr':df_fittings_other_arr,
                'gd_extra_note':survey_report.gd_extra_note
            })
        else:   
            survey_report.deck_fittings.all().delete()
            
            df_deck_names = request.POST.get('df_deck_name').split(',') if request.POST.get('df_deck_name') else ''
            df_deck_name_others = request.POST.get('df_deck_name_other').split(',') if request.POST.get('df_deck_name_other') else ''
            df_fittingss = request.POST.get('df_fittings').split(',') if request.POST.get('df_fittings') else ''
            df_fittings_others = request.POST.get('df_fittings_other').split(',') if request.POST.get('df_fittings_other') else ''
            df_numbers = request.POST.get('df_number').split(',') if request.POST.get('df_number') else ''
            df_sizes = request.POST.get('df_size').split(',') if request.POST.get('df_size') else ''
            df_locations = request.POST.get('df_location').split(',') if request.POST.get('df_location') else ''

            for index, df in enumerate(df_deck_names):
                deck_fittings = DeckFittings.objects.create(
                    df_deck_name=df_deck_names[index] if df_deck_names else '',
                    df_deck_name_other=df_deck_name_others[index] if df_deck_name_others else '',
                    df_fittings=df_fittingss[index] if df_fittingss else '',
                    df_fittings_other=df_fittings_others[index] if df_fittings_others else '',
                    df_number=df_numbers[index] if df_numbers else '',
                    df_size=df_sizes[index] if df_sizes else '',
                    df_location=df_locations[index] if df_locations else '',
                )
                survey_report.deck_fittings.add(deck_fittings)

            survey_report.deck_fittings_description = request.POST['deck_fittings_description']
            survey_report.deck_fittings_condition_rating = request.POST['deck_fittings_condition_rating']
            survey_report.deck_fittings_condition = request.POST['deck_fittings_condition']
            survey_report.gd_extra_note = request.POST['gd_extra_note']


            img_data = request.POST.get('img_data').replace("[","").replace("]","")
            img_data_arr = img_data.split(",")
            survey_report.deck_fitting_images.all().delete()
            for image_data in img_data_arr:
                url = GlobalConfiguration.api_b64_aws_s3_image_post("deck_fitting_images/",image_data)
                fnd_images = DeckFittingsImage.objects.create(
                    deck_fitting_images=url
                )
                survey_report.deck_fitting_images.add(fnd_images)

            survey_report.save()

            return JsonResponse({
                'code':'300'
            })


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step8_image(request):
    file_name = "ground_tackle_images/"+str(uuid.uuid4())+".jpg"
    image_data = request.POST.get('image_data')
    
    #image_data += "==" * ((4 - len(image_data) % 4) % 4)
    image_data = image_data.replace(" ","+")
    session = boto3.session.Session(aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_KEY)
    s3 = session.resource('s3')
    s3.Bucket("dls2018").put_object(Key=file_name, Body=base64.b64decode(image_data), ContentType='image/jpeg', ACL='public-read')
    url = settings.AWS_S3_URL+file_name

    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
    fnd_images = GroundTackleImage.objects.create(
        ground_tackle_images=str(url)
    )
    survey_report.ground_tackle_images.add(fnd_images)
    return JsonResponse({"code": str(url)})



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step8(request):
    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))

    survey_report.ground_tackle_description = request.POST['ground_tackle_description']
    survey_report.ground_tackle_condition_rating = request.POST['ground_tackle_condition_rating']
    survey_report.ground_tackle_condition = request.POST['ground_tackle_condition']
    survey_report.gd_extra_note = request.POST['gd_extra_note']
    survey_report.save()
    return JsonResponse({"code": "200","survey_report_id": str(survey_report.id)})



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step8_details(request):
    survey_report = None
    now = datetime.now() + timedelta(hours=1)
    ground_tackle_description = ''
    ground_tackle_condition_rating = ''
    ground_tackle_condition = ''
    ground_tackle_images_arr = []
    if request.POST['survey_report_id']:
        survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))

        request_time = 0
        if request.POST['updated_on'] != '0':
            dt = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            request_time = int(time.mktime(dt.timetuple()))
        if time.mktime(survey_report.updated_on.timetuple() if survey_report.updated_on else now.timetuple()) > request_time:

            ground_tackle_description = survey_report.ground_tackle_description
            ground_tackle_condition_rating = survey_report.ground_tackle_condition_rating
            ground_tackle_condition = survey_report.ground_tackle_condition


            for gimg in survey_report.ground_tackle_images.all():
                ground_tackle_images_arr.append(str(GlobalConfiguration.get_as_base64(str(gimg.ground_tackle_images)))[2:-1])

            return JsonResponse({
                'code':'200',
                'ground_tackle_description':ground_tackle_description,
                'ground_tackle_condition_rating':ground_tackle_condition_rating,
                'ground_tackle_condition':ground_tackle_condition,
                'ground_tackle_images_arr':ground_tackle_images_arr,
                'gd_extra_note':survey_report.gd_extra_note
            })
        else:    
            survey_report.ground_tackle_description = request.POST['ground_tackle_description']
            survey_report.ground_tackle_condition_rating = request.POST['ground_tackle_condition_rating']
            survey_report.ground_tackle_condition = request.POST['ground_tackle_condition']
            survey_report.gd_extra_note = request.POST['gd_extra_note']


            img_data = request.POST.get('img_data').replace("[","").replace("]","")
            img_data_arr = img_data.split(",")
            survey_report.ground_tackle_images.all().delete()
            for image_data in img_data_arr:
                url = GlobalConfiguration.api_b64_aws_s3_image_post("ground_tackle_images/",image_data)
                fnd_images = GroundTackleImage.objects.create(
                    ground_tackle_images=url
                )
                survey_report.ground_tackle_images.add(fnd_images)

            survey_report.save()
            
            return JsonResponse({
                'code':'300'
            })


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step9_image(request):
    file_name = "hull_comp_images/"+str(uuid.uuid4())+".jpg"
    image_data = request.POST.get('image_data')
    
    #image_data += "==" * ((4 - len(image_data) % 4) % 4)
    image_data = image_data.replace(" ","+")
    session = boto3.session.Session(aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_KEY)
    s3 = session.resource('s3')
    s3.Bucket("dls2018").put_object(Key=file_name, Body=base64.b64decode(image_data), ContentType='image/jpeg', ACL='public-read')
    url = settings.AWS_S3_URL+file_name

    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
    fnd_images = HullCompImage.objects.create(
        hull_comp_images=str(url)
    )
    survey_report.hull_comp_images.add(fnd_images)
    return JsonResponse({"code": str(url)})


@api_view(['POST'])
@permission_classes(( ))
@csrf_exempt
def test_json(request):
    img_data = request.POST.get('img_data').replace("[","").replace("]","")
    img_data_arr = img_data.split(",")
    for i in img_data_arr:
        url = GlobalConfiguration.api_b64_aws_s3_image_post("fendering_images/",i)
    return JsonResponse({"count": len(img_data_arr)})
    #outer_bullet = request.POST.get('outer_bullet')[1:-1]
    #outer_bullet = outer_bullet.replace("\\","")
    #inner_bullet = request.POST.get('inner_bullet')[1:-1]
    #inner_bullet = inner_bullet.replace("\\","")
    #return JsonResponse({"code": "200","outer_bullet": ast.literal_eval(outer_bullet), "inner_bullet": ast.literal_eval(inner_bullet)})


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step9(request):
    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
    
    survey_report.hc_additional_commentary = request.POST.get('additional_comments','')
    survey_report.gd_extra_note = request.POST['gd_extra_note']

    try:
        survey_report.hull_comp_description.all().delete()
        outer_bullet = request.POST.get('outer_bullet')[1:-1]
        outer_bullet = ast.literal_eval(outer_bullet.replace("\\",""))
        inner_bullet = request.POST.get('inner_bullet')[1:-1]
        inner_bullet = ast.literal_eval(inner_bullet.replace("\\",""))
        for j, inner_bullet in enumerate(inner_bullet):
            for k, val in enumerate(inner_bullet):
                hull_comp_description = HullCompBullet.objects.create(
                    outer_bullet=outer_bullet[j],
                    inner_bullet=val,
                )
                survey_report.hull_comp_description.add(hull_comp_description)
    except:
        pass
            
    
    survey_report.hull_comp_tank.all().delete()
    hc_tank_types = request.POST.get('tanktype').split(',') if request.POST.get('tanktype') else ''
    hc_tank_type_others = request.POST.get('hc_tank_type_other').split(',') if request.POST.get('hc_tank_type_other') else ''
    hc_filling_lines = request.POST.get('tanktypefillings').split(',') if request.POST.get('tanktypefillings') else ''
    hc_vents = request.POST.get('tanktypevents').split(',') if request.POST.get('tanktypevents') else ''
    for index, df in enumerate(hc_tank_types):
        hull_comp_tank = HullCompTank.objects.create(
            hc_tank_type=hc_tank_types[index] if hc_tank_types else '',
            hc_tank_type_other=hc_tank_type_others[index] if hc_tank_type_others else '',
            hc_filling_lines=hc_filling_lines[index] if hc_filling_lines else '',
            hc_vents=hc_vents[index] if hc_vents else '',
        )
        survey_report.hull_comp_tank.add(hull_comp_tank)
    
    survey_report.hull_comp_capacity.all().delete()
    hc_capacity_types = request.POST.get('capacitytype').split(',') if request.POST.get('capacitytype') else ''
    hc_capacity_vols = request.POST.get('capacitytypefillings').split(',') if request.POST.get('capacitytypefillings') else ''
    hc_capacity_unitss = request.POST.get('capacitytypevents').split(',') if request.POST.get('capacitytypevents') else ''
    for index, df in enumerate(hc_capacity_types):
        hull_comp_capacity = HullCompCapacity.objects.create(
            hc_capacity_type=hc_capacity_types[index] if hc_capacity_types else '',
            hc_capacity_vol=hc_capacity_vols[index] if hc_capacity_vols else '',
            hc_capacity_units=hc_capacity_unitss[index] if hc_capacity_unitss else '',
        )
        survey_report.hull_comp_capacity.add(hull_comp_capacity)
    survey_report.completed_on = timezone.now()
    survey_report.save()
    return JsonResponse({"code": "200","survey_report_id": str(survey_report.id)})



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step9_details(request):
    survey_report = None
    now = datetime.now() + timedelta(hours=1)
    hc_additional_commentary = ''
    outer_bullet = []
    inner_bullet = []
    hc_tanktype = []
    hc_tank_type_other = []
    hc_tanktypefillings = []
    hc_tanktypevents = []
    hc_capacitytype = []
    hc_capacitytypefillings = []
    hc_capacitytypevents = []
    if request.POST['survey_report_id']:
        survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))

        request_time = 0
        if request.POST['updated_on'] != '0':
            dt = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            request_time = int(time.mktime(dt.timetuple()))
        if time.mktime(survey_report.updated_on.timetuple() if survey_report.updated_on else now.timetuple()) > request_time:
                
            hc_additional_commentary = survey_report.hc_additional_commentary
            
            # hullcompartment outer bullet and inner bullet
            for br in survey_report.hull_comp_description.values_list('outer_bullet', flat=True).distinct():
                outer_bullet.append(br)
                inner_bullet_in = []
                for inner in survey_report.hull_comp_description.filter(outer_bullet__exact=br):
                    inner_bullet_in.append(inner.inner_bullet)
                inner_bullet.append(inner_bullet_in)
            

            for hc in survey_report.hull_comp_tank.all():
                hc_tanktype.append(hc.hc_tank_type)
                hc_tanktypefillings.append(hc.hc_filling_lines)
                hc_tanktypevents.append(hc.hc_vents)
                hc_tank_type_other.append(hc.hc_tank_type_other)

            for hcc in survey_report.hull_comp_capacity.all():
                hc_capacitytype.append(hcc.hc_capacity_type)
                hc_capacitytypefillings.append(hcc.hc_capacity_vol)
                hc_capacitytypevents.append(hcc.hc_capacity_units)

            hull_comp_images_arr = []
            for gimg in survey_report.hull_comp_images.all():
                hull_comp_images_arr.append(str(GlobalConfiguration.get_as_base64(str(gimg.hull_comp_images)))[2:-1])

            return JsonResponse({
                'code':'200',
                'updated_on':str(survey_report.updated_on).replace('T', ' ')[:19] if survey_report.updated_on else str(now).replace('T', ' ')[:19],
                'hc_additional_commentary':hc_additional_commentary,
                'outer_bullet':outer_bullet,
                'inner_bullet':inner_bullet,
                'hc_tanktype':hc_tanktype,
                'hc_tank_type_other':hc_tank_type_other,
                'hc_tanktypefillings':hc_tanktypefillings,
                'hc_tanktypevents':hc_tanktypevents,
                'hc_capacitytype':hc_capacitytype,
                'hc_capacitytypefillings':hc_capacitytypefillings,
                'hc_capacitytypevents':hc_capacitytypevents,
                'hull_comp_images_arr':hull_comp_images_arr,
                'gd_extra_note':survey_report.gd_extra_note
                })
        else:
            survey_report.hc_additional_commentary = request.POST.get('additional_comments','')
            survey_report.gd_extra_note = request.POST['gd_extra_note']
            try:
                survey_report.hull_comp_description.all().delete()
                outer_bullet = request.POST.get('outer_bullet')[1:-1]
                outer_bullet = ast.literal_eval(outer_bullet.replace("\\",""))
                inner_bullet = request.POST.get('inner_bullet')[1:-1]
                inner_bullet = ast.literal_eval(inner_bullet.replace("\\",""))
                for j, inner_bullet in enumerate(inner_bullet):
                    for k, val in enumerate(inner_bullet):
                        hull_comp_description = HullCompBullet.objects.create(
                            outer_bullet=outer_bullet[j],
                            inner_bullet=val,
                        )
                        survey_report.hull_comp_description.add(hull_comp_description)
            except:
                pass
                    
            survey_report.hull_comp_tank.all().delete()
            hc_tank_types = request.POST.get('tanktype').split(',') if request.POST.get('tanktype') else ''
            hc_tank_type_others = request.POST.get('hc_tank_type_other').split(',') if request.POST.get('hc_tank_type_other') else ''
            hc_filling_lines = request.POST.get('tanktypefillings').split(',') if request.POST.get('tanktypefillings') else ''
            hc_vents = request.POST.get('tanktypevents').split(',') if request.POST.get('tanktypevents') else ''
            for index, df in enumerate(hc_tank_types):
                hull_comp_tank = HullCompTank.objects.create(
                    hc_tank_type=hc_tank_types[index] if hc_tank_types else '',
                    hc_tank_type_other=hc_tank_type_others[index] if hc_tank_type_others else '',
                    hc_filling_lines=hc_filling_lines[index] if hc_filling_lines else '',
                    hc_vents=hc_vents[index] if hc_vents else '',
                )
                survey_report.hull_comp_tank.add(hull_comp_tank)
            
            survey_report.hull_comp_capacity.all().delete()
            hc_capacity_types = request.POST.get('capacitytype').split(',') if request.POST.get('capacitytype') else ''
            hc_capacity_vols = request.POST.get('capacitytypefillings').split(',') if request.POST.get('capacitytypefillings') else ''
            hc_capacity_unitss = request.POST.get('capacitytypevents').split(',') if request.POST.get('capacitytypevents') else ''
            for index, df in enumerate(hc_capacity_types):
                hull_comp_capacity = HullCompCapacity.objects.create(
                    hc_capacity_type=hc_capacity_types[index] if hc_capacity_types else '',
                    hc_capacity_vol=hc_capacity_vols[index] if hc_capacity_vols else '',
                    hc_capacity_units=hc_capacity_unitss[index] if hc_capacity_unitss else '',
                )
                survey_report.hull_comp_capacity.add(hull_comp_capacity)



            img_data = request.POST.get('img_data').replace("[","").replace("]","")
            img_data_arr = img_data.split(",")
            survey_report.hull_comp_images.all().delete()
            for image_data in img_data_arr:
                url = GlobalConfiguration.api_b64_aws_s3_image_post("hull_comp_images/",image_data)
                fnd_images = HullCompImage.objects.create(
                    hull_comp_images=url
                )
                survey_report.hull_comp_images.add(fnd_images)

            survey_report.updated_on = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            survey_report.save()
            return JsonResponse({
                'code':'300'
            })



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step10(request):
    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))

    survey_report.dh_description = request.POST['dh_description']
    survey_report.dha_condition_rating = request.POST['dha_condition_rating']
    survey_report.dha_condition = request.POST['dha_condition']
    survey_report.gd_extra_note = request.POST['gd_extra_note']


    survey_report.berthing_compartments.all().delete()
    dh_bc_outer_bullet = request.POST.get('dh_bc_outer_bullet')[1:-1]
    dh_bc_outer_bullet = ast.literal_eval(dh_bc_outer_bullet.replace("\\",""))
    dh_bc_inner_bullet = request.POST.get('dh_bc_inner_bullet')[1:-1]
    dh_bc_inner_bullet = ast.literal_eval(dh_bc_inner_bullet.replace("\\",""))
    for j, dh_bc_inner_bullet in enumerate(dh_bc_inner_bullet):
        for k, val in enumerate(dh_bc_inner_bullet):
            berthing_compartments = BerthingCompartments.objects.create(
                dh_bc_outer_bullet=dh_bc_outer_bullet[j],
                dh_bc_inner_bullet=val,
            )
            survey_report.berthing_compartments.add(berthing_compartments)


    survey_report.galley.all().delete()
    dh_g_outer_bullet = request.POST.get('dh_g_outer_bullet')[1:-1]
    dh_g_outer_bullet = ast.literal_eval(dh_g_outer_bullet.replace("\\",""))
    dh_g_inner_bullet = request.POST.get('dh_g_inner_bullet')[1:-1]
    dh_g_inner_bullet = ast.literal_eval(dh_g_inner_bullet.replace("\\",""))
    for j, dh_g_inner_bullet in enumerate(dh_g_inner_bullet):
        for k, val in enumerate(dh_g_inner_bullet):
            galley = Galley.objects.create(
                dh_g_outer_bullet=dh_g_outer_bullet[j],
                dh_g_inner_bullet=val,
            )
            survey_report.galley.add(galley)


    survey_report.mess_decks.all().delete()
    dh_md_outer_bullet = request.POST.get('dh_md_outer_bullet')[1:-1]
    dh_md_outer_bullet = ast.literal_eval(dh_md_outer_bullet.replace("\\",""))
    dh_md_inner_bullet = request.POST.get('dh_md_inner_bullet')[1:-1]
    dh_md_inner_bullet = ast.literal_eval(dh_md_inner_bullet.replace("\\",""))
    for j, dh_md_inner_bullet in enumerate(dh_md_inner_bullet):
        for k, val in enumerate(dh_md_inner_bullet):
            mess_decks = MessDecks.objects.create(
                dh_md_outer_bullet=dh_md_outer_bullet[j],
                dh_md_inner_bullet=val,
            )
            survey_report.mess_decks.add(mess_decks)


    survey_report.laundry.all().delete()
    dh_l_outer_bullet = request.POST.get('dh_l_outer_bullet')[1:-1]
    dh_l_outer_bullet = ast.literal_eval(dh_l_outer_bullet.replace("\\",""))
    dh_l_inner_bullet = request.POST.get('dh_l_inner_bullet')[1:-1]
    dh_l_inner_bullet = ast.literal_eval(dh_l_inner_bullet.replace("\\",""))
    for j, dh_l_inner_bullet in enumerate(dh_l_inner_bullet):
        for k, val in enumerate(dh_l_inner_bullet):
            laundry = Laundry.objects.create(
                dh_l_outer_bullet=dh_l_outer_bullet[j],
                dh_l_inner_bullet=val,
            )
            survey_report.laundry.add(laundry)


    survey_report.hospital.all().delete()
    dh_h_outer_bullet = request.POST.get('dh_h_outer_bullet')[1:-1]
    dh_h_outer_bullet = ast.literal_eval(dh_h_outer_bullet.replace("\\",""))
    dh_h_inner_bullet = request.POST.get('dh_h_inner_bullet')[1:-1]
    dh_h_inner_bullet = ast.literal_eval(dh_h_inner_bullet.replace("\\",""))
    for j, dh_h_inner_bullet in enumerate(dh_h_inner_bullet):
        for k, val in enumerate(dh_h_inner_bullet):
            hospital = Hospital.objects.create(
                dh_h_outer_bullet=dh_h_outer_bullet[j],
                dh_h_inner_bullet=val,
            )
            survey_report.hospital.add(hospital)


    survey_report.recreation_room.all().delete()
    dh_rr_outer_bullet = request.POST.get('dh_rr_outer_bullet')[1:-1]
    dh_rr_outer_bullet = ast.literal_eval(dh_rr_outer_bullet.replace("\\",""))
    dh_rr_inner_bullet = request.POST.get('dh_rr_inner_bullet')[1:-1]
    dh_rr_inner_bullet = ast.literal_eval(dh_rr_inner_bullet.replace("\\",""))
    for j, dh_rr_inner_bullet in enumerate(dh_rr_inner_bullet):
        for k, val in enumerate(dh_rr_inner_bullet):
            recreation_room = RecreationRoom.objects.create(
                dh_rr_outer_bullet=dh_rr_outer_bullet[j],
                dh_rr_inner_bullet=val,
            )
            survey_report.recreation_room.add(recreation_room)


    survey_report.theater_room.all().delete()
    dh_tr_outer_bullet = request.POST.get('dh_tr_outer_bullet')[1:-1]
    dh_tr_outer_bullet = ast.literal_eval(dh_tr_outer_bullet.replace("\\",""))
    dh_tr_inner_bullet = request.POST.get('dh_tr_inner_bullet')[1:-1]
    dh_tr_inner_bullet = ast.literal_eval(dh_tr_inner_bullet.replace("\\",""))
    for j, dh_tr_inner_bullet in enumerate(dh_tr_inner_bullet):
        for k, val in enumerate(dh_tr_inner_bullet):
            theater_room = TheaterRoom.objects.create(
                dh_tr_outer_bullet=dh_tr_outer_bullet[j],
                dh_tr_inner_bullet=val,
            )
            survey_report.theater_room.add(theater_room)


    survey_report.helo_reception_room.all().delete()
    dh_hrr_outer_bullet = request.POST.get('dh_hrr_outer_bullet')[1:-1]
    dh_hrr_outer_bullet = ast.literal_eval(dh_hrr_outer_bullet.replace("\\",""))
    dh_hrr_inner_bullet = request.POST.get('dh_hrr_inner_bullet')[1:-1]
    dh_hrr_inner_bullet = ast.literal_eval(dh_hrr_inner_bullet.replace("\\",""))
    for j, dh_hrr_inner_bullet in enumerate(dh_hrr_inner_bullet):
        for k, val in enumerate(dh_hrr_inner_bullet):
            helo_reception_room = HeloReceptionRoom.objects.create(
                dh_hrr_outer_bullet=dh_hrr_outer_bullet[j],
                dh_hrr_inner_bullet=val,
            )
            survey_report.helo_reception_room.add(helo_reception_room)


    survey_report.public_sanitary_facilities.all().delete()
    dh_psf_outer_bullet = request.POST.get('dh_psf_outer_bullet')[1:-1]
    dh_psf_outer_bullet = ast.literal_eval(dh_psf_outer_bullet.replace("\\",""))
    dh_psf_inner_bullet = request.POST.get('dh_psf_inner_bullet')[1:-1]
    dh_psf_inner_bullet = ast.literal_eval(dh_psf_inner_bullet.replace("\\",""))
    for j, dh_psf_inner_bullet in enumerate(dh_psf_inner_bullet):
        for k, val in enumerate(dh_psf_inner_bullet):
            public_sanitary_facilities = PublicSanitaryFacilities.objects.create(
                dh_psf_outer_bullet=dh_psf_outer_bullet[j],
                dh_psf_inner_bullet=val,
            )
            survey_report.public_sanitary_facilities.add(public_sanitary_facilities)


    survey_report.other_deck_house_category.all().delete()
    dh_odhc_outer_bullet = request.POST.get('dh_odhc_outer_bullet')[1:-1]
    dh_odhc_outer_bullet = ast.literal_eval(dh_odhc_outer_bullet.replace("\\",""))
    dh_odhc_inner_bullet = request.POST.get('dh_odhc_inner_bullet')[1:-1]
    dh_odhc_inner_bullet = ast.literal_eval(dh_odhc_inner_bullet.replace("\\",""))
    for j, dh_odhc_inner_bullet in enumerate(dh_odhc_inner_bullet):
        for k, val in enumerate(dh_odhc_inner_bullet):
            other_deck_house_category = OtherDeckHouseCategory.objects.create(
                dh_odhc_outer_bullet=dh_odhc_outer_bullet[j],
                dh_odhc_inner_bullet=val,
            )
            survey_report.other_deck_house_category.add(other_deck_house_category)


    survey_report.save()
    return JsonResponse({"code": "200","survey_report_id": str(survey_report.id)})



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step10_details(request):
    survey_report = None
    now = datetime.now() + timedelta(hours=1)
    dh_description = ''
    dha_condition_rating = ''
    dha_condition = ''
    dh_bc_outer_bullet = []
    dh_bc_inner_bullet = []
    dh_g_outer_bullet = []
    dh_g_inner_bullet = []
    dh_md_outer_bullet = []
    dh_md_inner_bullet = []
    dh_l_outer_bullet = []
    dh_l_inner_bullet = []
    dh_h_outer_bullet = []
    dh_h_inner_bullet = []
    dh_rr_outer_bullet = []
    dh_rr_inner_bullet = []
    dh_tr_outer_bullet = []
    dh_tr_inner_bullet = []
    dh_hrr_outer_bullet = []
    dh_hrr_inner_bullet = []
    dh_psf_outer_bullet = []
    dh_psf_inner_bullet = []
    dh_odhc_outer_bullet = []
    dh_odhc_inner_bullet = []
    if request.POST['survey_report_id']:
        survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
        
        request_time = 0
        if request.POST['updated_on'] != '0':
            dt = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            request_time = int(time.mktime(dt.timetuple()))
        if time.mktime(survey_report.updated_on.timetuple() if survey_report.updated_on else now.timetuple()) > request_time:
                    
            dh_description = survey_report.dh_description
            dha_condition_rating = survey_report.dha_condition_rating
            dha_condition = survey_report.dha_condition

            for br in survey_report.berthing_compartments.values_list('dh_bc_outer_bullet', flat=True).distinct():
                dh_bc_outer_bullet.append(br)
                inner_bullet_in = []
                for inner in survey_report.berthing_compartments.filter(dh_bc_outer_bullet__exact=br):
                    inner_bullet_in.append(inner.dh_bc_inner_bullet)
                dh_bc_inner_bullet.append(inner_bullet_in)

            
            for br in survey_report.galley.values_list('dh_g_outer_bullet', flat=True).distinct():
                dh_g_outer_bullet.append(br)
                inner_bullet_in = []
                for inner in survey_report.galley.filter(dh_g_outer_bullet__exact=br):
                    inner_bullet_in.append(inner.dh_g_inner_bullet)
                dh_g_inner_bullet.append(inner_bullet_in)
            

            for br in survey_report.mess_decks.values_list('dh_md_outer_bullet', flat=True).distinct():
                dh_md_outer_bullet.append(br)
                inner_bullet_in = []
                for inner in survey_report.mess_decks.filter(dh_md_outer_bullet__exact=br):
                    inner_bullet_in.append(inner.dh_md_inner_bullet)
                dh_md_inner_bullet.append(inner_bullet_in)

            
            for br in survey_report.laundry.values_list('dh_l_outer_bullet', flat=True).distinct():
                dh_l_outer_bullet.append(br)
                inner_bullet_in = []
                for inner in survey_report.laundry.filter(dh_l_outer_bullet__exact=br):
                    inner_bullet_in.append(inner.dh_l_inner_bullet)
                dh_l_inner_bullet.append(inner_bullet_in)

            
            for br in survey_report.hospital.values_list('dh_h_outer_bullet', flat=True).distinct():
                dh_h_outer_bullet.append(br)
                inner_bullet_in = []
                for inner in survey_report.hospital.filter(dh_h_outer_bullet__exact=br):
                    inner_bullet_in.append(inner.dh_h_inner_bullet)
                dh_h_inner_bullet.append(inner_bullet_in)

            
            for br in survey_report.recreation_room.values_list('dh_rr_outer_bullet', flat=True).distinct():
                dh_rr_outer_bullet.append(br)
                inner_bullet_in = []
                for inner in survey_report.recreation_room.filter(dh_rr_outer_bullet__exact=br):
                    inner_bullet_in.append(inner.dh_rr_inner_bullet)
                dh_rr_inner_bullet.append(inner_bullet_in)

            
            for br in survey_report.theater_room.values_list('dh_tr_outer_bullet', flat=True).distinct():
                dh_tr_outer_bullet.append(br)
                inner_bullet_in = []
                for inner in survey_report.theater_room.filter(dh_tr_outer_bullet__exact=br):
                    inner_bullet_in.append(inner.dh_tr_inner_bullet)
                dh_tr_inner_bullet.append(inner_bullet_in)

            
            for br in survey_report.helo_reception_room.values_list('dh_hrr_outer_bullet', flat=True).distinct():
                dh_hrr_outer_bullet.append(br)
                inner_bullet_in = []
                for inner in survey_report.helo_reception_room.filter(dh_hrr_outer_bullet__exact=br):
                    inner_bullet_in.append(inner.dh_hrr_inner_bullet)
                dh_hrr_inner_bullet.append(inner_bullet_in)

            
            for br in survey_report.public_sanitary_facilities.values_list('dh_psf_outer_bullet', flat=True).distinct():
                dh_psf_outer_bullet.append(br)
                inner_bullet_in = []
                for inner in survey_report.public_sanitary_facilities.filter(dh_psf_outer_bullet__exact=br):
                    inner_bullet_in.append(inner.dh_psf_inner_bullet)
                dh_psf_inner_bullet.append(inner_bullet_in)

            
            for br in survey_report.other_deck_house_category.values_list('dh_odhc_outer_bullet', flat=True).distinct():
                dh_odhc_outer_bullet.append(br)
                inner_bullet_in = []
                for inner in survey_report.other_deck_house_category.filter(dh_odhc_outer_bullet__exact=br):
                    inner_bullet_in.append(inner.dh_odhc_inner_bullet)
                dh_odhc_inner_bullet.append(inner_bullet_in)

            
            deck_house_image_arr = []
            for gimg in survey_report.deck_house_image.all():
                deck_house_image_arr.append(str(GlobalConfiguration.get_as_base64(str(gimg.deck_house_image)))[2:-1])

            return JsonResponse({
                'code':'200',
                'updated_on':str(survey_report.updated_on).replace('T', ' ')[:19] if survey_report.updated_on else str(now).replace('T', ' ')[:19],
                'dh_description':dh_description,
                'dha_condition_rating':dha_condition_rating,
                'dha_condition':dha_condition,
                'dh_bc_outer_bullet':dh_bc_outer_bullet,
                'dh_bc_inner_bullet':dh_bc_inner_bullet,
                'dh_g_outer_bullet':dh_g_outer_bullet,
                'dh_g_inner_bullet':dh_g_inner_bullet,
                'dh_md_outer_bullet':dh_md_outer_bullet,
                'dh_md_inner_bullet':dh_md_inner_bullet,
                'dh_l_outer_bullet':dh_l_outer_bullet,
                'dh_l_inner_bullet':dh_l_inner_bullet,
                'dh_h_outer_bullet':dh_h_outer_bullet,
                'dh_h_inner_bullet':dh_h_inner_bullet,
                'dh_rr_outer_bullet':dh_rr_outer_bullet,
                'dh_rr_inner_bullet':dh_rr_inner_bullet,
                'dh_tr_outer_bullet':dh_tr_outer_bullet,
                'dh_tr_inner_bullet':dh_tr_inner_bullet,
                'dh_hrr_outer_bullet':dh_hrr_outer_bullet,
                'dh_hrr_inner_bullet':dh_hrr_inner_bullet,
                'dh_psf_outer_bullet':dh_psf_outer_bullet,
                'dh_psf_inner_bullet':dh_psf_inner_bullet,
                'dh_odhc_outer_bullet':dh_odhc_outer_bullet,
                'dh_odhc_inner_bullet':dh_odhc_inner_bullet,
                'deck_house_image_arr':deck_house_image_arr,
                'gd_extra_note':survey_report.gd_extra_note
            })
        else:
            
            survey_report.dh_description = request.POST['dh_description']
            survey_report.dha_condition_rating = request.POST['dha_condition_rating']
            survey_report.dha_condition = request.POST['dha_condition']
            survey_report.gd_extra_note = request.POST['gd_extra_note']


            survey_report.berthing_compartments.all().delete()
            dh_bc_outer_bullet = request.POST.get('dh_bc_outer_bullet')[1:-1]
            dh_bc_outer_bullet = ast.literal_eval(dh_bc_outer_bullet.replace("\\",""))
            dh_bc_inner_bullet = request.POST.get('dh_bc_inner_bullet')[1:-1]
            dh_bc_inner_bullet = ast.literal_eval(dh_bc_inner_bullet.replace("\\",""))
            for j, dh_bc_inner_bullet in enumerate(dh_bc_inner_bullet):
                for k, val in enumerate(dh_bc_inner_bullet):
                    berthing_compartments = BerthingCompartments.objects.create(
                        dh_bc_outer_bullet=dh_bc_outer_bullet[j],
                        dh_bc_inner_bullet=val,
                    )
                    survey_report.berthing_compartments.add(berthing_compartments)


            survey_report.galley.all().delete()
            dh_g_outer_bullet = request.POST.get('dh_g_outer_bullet')[1:-1]
            dh_g_outer_bullet = ast.literal_eval(dh_g_outer_bullet.replace("\\",""))
            dh_g_inner_bullet = request.POST.get('dh_g_inner_bullet')[1:-1]
            dh_g_inner_bullet = ast.literal_eval(dh_g_inner_bullet.replace("\\",""))
            for j, dh_g_inner_bullet in enumerate(dh_g_inner_bullet):
                for k, val in enumerate(dh_g_inner_bullet):
                    galley = Galley.objects.create(
                        dh_g_outer_bullet=dh_g_outer_bullet[j],
                        dh_g_inner_bullet=val,
                    )
                    survey_report.galley.add(galley)


            survey_report.mess_decks.all().delete()
            dh_md_outer_bullet = request.POST.get('dh_md_outer_bullet')[1:-1]
            dh_md_outer_bullet = ast.literal_eval(dh_md_outer_bullet.replace("\\",""))
            dh_md_inner_bullet = request.POST.get('dh_md_inner_bullet')[1:-1]
            dh_md_inner_bullet = ast.literal_eval(dh_md_inner_bullet.replace("\\",""))
            for j, dh_md_inner_bullet in enumerate(dh_md_inner_bullet):
                for k, val in enumerate(dh_md_inner_bullet):
                    mess_decks = MessDecks.objects.create(
                        dh_md_outer_bullet=dh_md_outer_bullet[j],
                        dh_md_inner_bullet=val,
                    )
                    survey_report.mess_decks.add(mess_decks)


            survey_report.laundry.all().delete()
            dh_l_outer_bullet = request.POST.get('dh_l_outer_bullet')[1:-1]
            dh_l_outer_bullet = ast.literal_eval(dh_l_outer_bullet.replace("\\",""))
            dh_l_inner_bullet = request.POST.get('dh_l_inner_bullet')[1:-1]
            dh_l_inner_bullet = ast.literal_eval(dh_l_inner_bullet.replace("\\",""))
            for j, dh_l_inner_bullet in enumerate(dh_l_inner_bullet):
                for k, val in enumerate(dh_l_inner_bullet):
                    laundry = Laundry.objects.create(
                        dh_l_outer_bullet=dh_l_outer_bullet[j],
                        dh_l_inner_bullet=val,
                    )
                    survey_report.laundry.add(laundry)


            survey_report.hospital.all().delete()
            dh_h_outer_bullet = request.POST.get('dh_h_outer_bullet')[1:-1]
            dh_h_outer_bullet = ast.literal_eval(dh_h_outer_bullet.replace("\\",""))
            dh_h_inner_bullet = request.POST.get('dh_h_inner_bullet')[1:-1]
            dh_h_inner_bullet = ast.literal_eval(dh_h_inner_bullet.replace("\\",""))
            for j, dh_h_inner_bullet in enumerate(dh_h_inner_bullet):
                for k, val in enumerate(dh_h_inner_bullet):
                    hospital = Hospital.objects.create(
                        dh_h_outer_bullet=dh_h_outer_bullet[j],
                        dh_h_inner_bullet=val,
                    )
                    survey_report.hospital.add(hospital)


            survey_report.recreation_room.all().delete()
            dh_rr_outer_bullet = request.POST.get('dh_rr_outer_bullet')[1:-1]
            dh_rr_outer_bullet = ast.literal_eval(dh_rr_outer_bullet.replace("\\",""))
            dh_rr_inner_bullet = request.POST.get('dh_rr_inner_bullet')[1:-1]
            dh_rr_inner_bullet = ast.literal_eval(dh_rr_inner_bullet.replace("\\",""))
            for j, dh_rr_inner_bullet in enumerate(dh_rr_inner_bullet):
                for k, val in enumerate(dh_rr_inner_bullet):
                    recreation_room = RecreationRoom.objects.create(
                        dh_rr_outer_bullet=dh_rr_outer_bullet[j],
                        dh_rr_inner_bullet=val,
                    )
                    survey_report.recreation_room.add(recreation_room)


            survey_report.theater_room.all().delete()
            dh_tr_outer_bullet = request.POST.get('dh_tr_outer_bullet')[1:-1]
            dh_tr_outer_bullet = ast.literal_eval(dh_tr_outer_bullet.replace("\\",""))
            dh_tr_inner_bullet = request.POST.get('dh_tr_inner_bullet')[1:-1]
            dh_tr_inner_bullet = ast.literal_eval(dh_tr_inner_bullet.replace("\\",""))
            for j, dh_tr_inner_bullet in enumerate(dh_tr_inner_bullet):
                for k, val in enumerate(dh_tr_inner_bullet):
                    theater_room = TheaterRoom.objects.create(
                        dh_tr_outer_bullet=dh_tr_outer_bullet[j],
                        dh_tr_inner_bullet=val,
                    )
                    survey_report.theater_room.add(theater_room)


            survey_report.helo_reception_room.all().delete()
            dh_hrr_outer_bullet = request.POST.get('dh_hrr_outer_bullet')[1:-1]
            dh_hrr_outer_bullet = ast.literal_eval(dh_hrr_outer_bullet.replace("\\",""))
            dh_hrr_inner_bullet = request.POST.get('dh_hrr_inner_bullet')[1:-1]
            dh_hrr_inner_bullet = ast.literal_eval(dh_hrr_inner_bullet.replace("\\",""))
            for j, dh_hrr_inner_bullet in enumerate(dh_hrr_inner_bullet):
                for k, val in enumerate(dh_hrr_inner_bullet):
                    helo_reception_room = HeloReceptionRoom.objects.create(
                        dh_hrr_outer_bullet=dh_hrr_outer_bullet[j],
                        dh_hrr_inner_bullet=val,
                    )
                    survey_report.helo_reception_room.add(helo_reception_room)


            survey_report.public_sanitary_facilities.all().delete()
            dh_psf_outer_bullet = request.POST.get('dh_psf_outer_bullet')[1:-1]
            dh_psf_outer_bullet = ast.literal_eval(dh_psf_outer_bullet.replace("\\",""))
            dh_psf_inner_bullet = request.POST.get('dh_psf_inner_bullet')[1:-1]
            dh_psf_inner_bullet = ast.literal_eval(dh_psf_inner_bullet.replace("\\",""))
            for j, dh_psf_inner_bullet in enumerate(dh_psf_inner_bullet):
                for k, val in enumerate(dh_psf_inner_bullet):
                    public_sanitary_facilities = PublicSanitaryFacilities.objects.create(
                        dh_psf_outer_bullet=dh_psf_outer_bullet[j],
                        dh_psf_inner_bullet=val,
                    )
                    survey_report.public_sanitary_facilities.add(public_sanitary_facilities)


            survey_report.other_deck_house_category.all().delete()
            dh_odhc_outer_bullet = request.POST.get('dh_odhc_outer_bullet')[1:-1]
            dh_odhc_outer_bullet = ast.literal_eval(dh_odhc_outer_bullet.replace("\\",""))
            dh_odhc_inner_bullet = request.POST.get('dh_odhc_inner_bullet')[1:-1]
            dh_odhc_inner_bullet = ast.literal_eval(dh_odhc_inner_bullet.replace("\\",""))
            for j, dh_odhc_inner_bullet in enumerate(dh_odhc_inner_bullet):
                for k, val in enumerate(dh_odhc_inner_bullet):
                    other_deck_house_category = OtherDeckHouseCategory.objects.create(
                        dh_odhc_outer_bullet=dh_odhc_outer_bullet[j],
                        dh_odhc_inner_bullet=val,
                    )
                    survey_report.other_deck_house_category.add(other_deck_house_category)


            img_data = request.POST.get('img_data').replace("[","").replace("]","")
            img_data_arr = img_data.split(",")
            survey_report.deck_house_image.all().delete()
            for image_data in img_data_arr:
                url = GlobalConfiguration.api_b64_aws_s3_image_post("deck_house_images/",image_data)
                fnd_images = DeckHouseImage.objects.create(
                    deck_house_image=url
                )
                survey_report.deck_house_image.add(fnd_images)

            survey_report.updated_on = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            survey_report.save()
            return JsonResponse({
                'code':'300'
            })



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step10_image(request):
    file_name = "deck_house_images/"+str(uuid.uuid4())+".jpg"
    image_data = request.POST.get('image_data')
    
    #image_data += "==" * ((4 - len(image_data) % 4) % 4)
    image_data = image_data.replace(" ","+")
    session = boto3.session.Session(aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_KEY)
    s3 = session.resource('s3')
    s3.Bucket("dls2018").put_object(Key=file_name, Body=base64.b64decode(image_data), ContentType='image/jpeg', ACL='public-read')
    url = settings.AWS_S3_URL+file_name

    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
    fnd_images = DeckHouseImage.objects.create(
        deck_house_image=str(url),
        deck_house_image_caption=''
    )
    survey_report.deck_house_image.add(fnd_images)
    return JsonResponse({"code": str(url)})


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step11(request):
    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))

    survey_report.ph_description = request.POST['ph_description']
    survey_report.pe_condition_rating = request.POST['pe_condition_rating']
    survey_report.pe_condition = request.POST['pe_condition']
    survey_report.gd_extra_note = request.POST['gd_extra_note']
    
    survey_report.pilothouse_equipments.all().delete()
    pe_outer_bullet = GlobalConfiguration.str_replace(request.POST.get('pe_outer_bullet')).split(',') if request.POST.get('pe_outer_bullet') else ''
    for i, x in enumerate(pe_outer_bullet):
        if x != '':
            pilothouse_equipments = PilothouseEquipments.objects.create(
                pe_outer_bullet=pe_outer_bullet[i] if pe_outer_bullet else '',
            )
            survey_report.pilothouse_equipments.add(pilothouse_equipments)


    survey_report.save()
    return JsonResponse({"code": "200","survey_report_id": str(survey_report.id)})



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step11_details(request):
    survey_report = None
    now = datetime.now() + timedelta(hours=1)
    ph_description = ''
    pe_condition_rating = ''
    pe_condition = ''
    pe_outer_bullet = []
    if request.POST['survey_report_id']:
        survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
        
        request_time = 0
        if request.POST['updated_on'] != '0':
            dt = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            request_time = int(time.mktime(dt.timetuple()))
        if time.mktime(survey_report.updated_on.timetuple() if survey_report.updated_on else now.timetuple()) > request_time:
            ph_description = survey_report.ph_description
            pe_condition_rating = survey_report.pe_condition_rating
            pe_condition = survey_report.pe_condition

            for hc in survey_report.pilothouse_equipments.all():
                pe_outer_bullet.append(hc.pe_outer_bullet)

            
            pilot_house_image_arr = []
            for gimg in survey_report.pilot_house_image.all():
                pilot_house_image_arr.append(str(GlobalConfiguration.get_as_base64(str(gimg.pilot_house_image)))[2:-1])
                
            return JsonResponse({
                'code':'200',
                'updated_on':str(survey_report.updated_on).replace('T', ' ')[:19] if survey_report.updated_on else str(now).replace('T', ' ')[:19],
                'ph_description':ph_description,
                'pe_condition_rating':pe_condition_rating,
                'pe_condition':pe_condition,
                'pe_outer_bullet':pe_outer_bullet,
                'pilot_house_image_arr':pilot_house_image_arr,
                'gd_extra_note':survey_report.gd_extra_note
            })
        else:
                    
            survey_report.ph_description = request.POST['ph_description']
            survey_report.pe_condition_rating = request.POST['pe_condition_rating']
            survey_report.pe_condition = request.POST['pe_condition']
            survey_report.gd_extra_note = request.POST['gd_extra_note']
            
            survey_report.pilothouse_equipments.all().delete()
            pe_outer_bullet = GlobalConfiguration.str_replace(request.POST.get('pe_outer_bullet')).split(',') if request.POST.get('pe_outer_bullet') else ''
            for i, x in enumerate(pe_outer_bullet):
                if x != '':
                    pilothouse_equipments = PilothouseEquipments.objects.create(
                        pe_outer_bullet=pe_outer_bullet[i] if pe_outer_bullet else '',
                    )
                    survey_report.pilothouse_equipments.add(pilothouse_equipments)

            
            img_data = request.POST.get('img_data').replace("[","").replace("]","")
            img_data_arr = img_data.split(",")
            survey_report.pilot_house_image.all().delete()
            for image_data in img_data_arr:
                url = GlobalConfiguration.api_b64_aws_s3_image_post("pilot_house_images/",image_data)
                fnd_images = PilotHouseImage.objects.create(
                    pilot_house_image=url
                )
                survey_report.pilot_house_image.add(fnd_images)

            survey_report.updated_on = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            survey_report.save()
            return JsonResponse({
                'code':'300'
            })


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step11_image(request):
    file_name = "pilot_house_images/"+str(uuid.uuid4())+".jpg"
    image_data = request.POST.get('image_data')
    
    #image_data += "==" * ((4 - len(image_data) % 4) % 4)
    image_data = image_data.replace(" ","+")
    session = boto3.session.Session(aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_KEY)
    s3 = session.resource('s3')
    s3.Bucket("dls2018").put_object(Key=file_name, Body=base64.b64decode(image_data), ContentType='image/jpeg', ACL='public-read')
    url = settings.AWS_S3_URL+file_name

    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
    fnd_images = PilotHouseImage.objects.create(
        pilot_house_image=str(url),
        pilot_house_image_caption=''
    )
    survey_report.pilot_house_image.add(fnd_images)
    return JsonResponse({"code": str(url)})


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step12(request):
    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))

    survey_report.ssc_condition = request.POST['ssc_condition']
    survey_report.ptc_condition = request.POST['ptc_condition']
    survey_report.pdc_condition = request.POST['pdc_condition']
    survey_report.fdc_condition = request.POST['fdc_condition']
    survey_report.mdc_condition = request.POST['mdc_condition']
    survey_report.osec_condition = request.POST['osec_condition']
    survey_report.seo_condition_rating = request.POST['seo_condition_rating']
    survey_report.seo_condition = request.POST['seo_condition']
    survey_report.gd_extra_note = request.POST['gd_extra_note']

    survey_report.save()
    return HttpResponse(json.dumps({'survey_report_id': str(survey_report.id)}))


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step12_details(request):
    survey_report = None
    now = datetime.now() + timedelta(hours=1)
    if request.POST['survey_report_id']:
        survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
        
        request_time = 0
        if request.POST['updated_on'] != '0':
            dt = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            request_time = int(time.mktime(dt.timetuple()))
        if time.mktime(survey_report.updated_on.timetuple() if survey_report.updated_on else now.timetuple()) > request_time:
                    
            ssc_condition = survey_report.ssc_condition
            ptc_condition = survey_report.ptc_condition
            pdc_condition = survey_report.pdc_condition
            fdc_condition = survey_report.fdc_condition
            mdc_condition = survey_report.mdc_condition
            osec_condition = survey_report.osec_condition
            seo_condition_rating = survey_report.seo_condition_rating
            seo_condition = survey_report.seo_condition


            data = {
                'ssc_condition':ssc_condition,
                'ptc_condition':ptc_condition,
                'pdc_condition':pdc_condition,
                'fdc_condition':fdc_condition,
                'mdc_condition':mdc_condition,
                'osec_condition':osec_condition,
                'seo_condition_rating':seo_condition_rating,
                'seo_condition':seo_condition,
                'gd_extra_note':survey_report.gd_extra_note
            }


            super_structure_image_arr = []
            for gimg in survey_report.super_structure_image.all():
                super_structure_image_arr.append(str(GlobalConfiguration.get_as_base64(str(gimg.super_structure_image)))[2:-1])
    
            return JsonResponse({
                'code':'200',
                'updated_on':str(survey_report.updated_on).replace('T', ' ')[:19] if survey_report.updated_on else str(now).replace('T', ' ')[:19],
                'data':data,
                'super_structure_image_arr':super_structure_image_arr
            })
        else:
                    
            survey_report.ssc_condition = request.POST['ssc_condition']
            survey_report.ptc_condition = request.POST['ptc_condition']
            survey_report.pdc_condition = request.POST['pdc_condition']
            survey_report.fdc_condition = request.POST['fdc_condition']
            survey_report.mdc_condition = request.POST['mdc_condition']
            survey_report.osec_condition = request.POST['osec_condition']
            survey_report.seo_condition_rating = request.POST['seo_condition_rating']
            survey_report.seo_condition = request.POST['seo_condition']
            survey_report.gd_extra_note = request.POST['gd_extra_note']


            img_data = request.POST.get('img_data').replace("[","").replace("]","")
            img_data_arr = img_data.split(",")
            survey_report.super_structure_image.all().delete()
            for image_data in img_data_arr:
                url = GlobalConfiguration.api_b64_aws_s3_image_post("super_structure_images/",image_data)
                fnd_images = SuperStructureImage.objects.create(
                    super_structure_image=url
                )
                survey_report.super_structure_image.add(fnd_images)

            survey_report.updated_on = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            survey_report.save()
            return JsonResponse({
                'code':'300'
            })


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step12_image(request):
    file_name = "super_structure_images/"+str(uuid.uuid4())+".jpg"
    image_data = request.POST.get('image_data')
    
    #image_data += "==" * ((4 - len(image_data) % 4) % 4)
    image_data = image_data.replace(" ","+")
    session = boto3.session.Session(aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_KEY)
    s3 = session.resource('s3')
    s3.Bucket("dls2018").put_object(Key=file_name, Body=base64.b64decode(image_data), ContentType='image/jpeg', ACL='public-read')
    url = settings.AWS_S3_URL+file_name

    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
    fnd_images = SuperStructureImage.objects.create(
        super_structure_image=str(url),
        super_structure_image_caption=''
    )
    survey_report.super_structure_image.add(fnd_images)
    return JsonResponse({"code": str(url)})


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step13(request):
    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))

    survey_report.m_mpm_description = request.POST['m_mpm_description']
    survey_report.m_mpm_condition_rating = request.POST['m_mpm_condition_rating']
    survey_report.m_mpm_condition = request.POST['m_mpm_condition']
    survey_report.m_eo_description = request.POST['m_eo_description']
    survey_report.m_eo_condition_rating = request.POST['m_eo_condition_rating']
    survey_report.m_se_description = request.POST['m_se_description']
    survey_report.m_se_condition_rating = request.POST['m_se_condition_rating']
    survey_report.gd_extra_note = request.POST['gd_extra_note']
    
    survey_report.auxiliary_machinery.all().delete()
    m_am_outer_bullet = request.POST.get('m_am_outer_bullet')[1:-1]
    m_am_outer_bullet = ast.literal_eval(m_am_outer_bullet.replace("\\",""))
    m_am_inner_bullet = request.POST.get('m_am_inner_bullet')[1:-1]
    m_am_inner_bullet = ast.literal_eval(m_am_inner_bullet.replace("\\",""))
    m_am_rating = request.POST.get('m_am_rating')[1:-1]
    m_am_rating = ast.literal_eval(m_am_rating.replace("\\",""))
    for j, m_am_inner_bullet in enumerate(m_am_inner_bullet):
        for k, val in enumerate(m_am_inner_bullet):
            auxiliary_machinery = AuxiliaryMachinery.objects.create(
                m_am_outer_bullet=m_am_outer_bullet[j],
                m_am_inner_bullet=val,
                m_am_rating=m_am_rating[j][k],
            )
            survey_report.auxiliary_machinery.add(auxiliary_machinery)


    survey_report.save()
    return HttpResponse(json.dumps({'survey_report_id': str(survey_report.id)}))


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step13_details(request):
    survey_report = None
    now = datetime.now() + timedelta(hours=1)
    m_mpm_description = ''
    m_mpm_condition_rating = ''
    m_mpm_condition = ''
    m_eo_description = ''
    m_eo_condition_rating = ''
    m_se_description = ''
    m_se_condition_rating = ''
    m_am_outer_bullet = []
    m_am_inner_bullet = []
    m_am_rating = []
    if request.POST['survey_report_id']:
        survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
        
        request_time = 0
        if request.POST['updated_on'] != '0':
            dt = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            request_time = int(time.mktime(dt.timetuple()))
        if time.mktime(survey_report.updated_on.timetuple() if survey_report.updated_on else now.timetuple()) > request_time:
                    
            m_mpm_description = survey_report.m_mpm_description
            m_mpm_condition_rating = survey_report.m_mpm_condition_rating
            m_mpm_condition = survey_report.m_mpm_condition
            m_eo_description = survey_report.m_eo_description 
            m_eo_condition_rating = survey_report.m_eo_condition_rating
            m_se_description = survey_report.m_se_description
            m_se_condition_rating = survey_report.m_se_condition_rating


            for br in survey_report.auxiliary_machinery.values_list('m_am_outer_bullet', flat=True).distinct():
                m_am_outer_bullet.append(br)
                inner_bullet_in = []
                inner_bullet_in_rating = []
                for inner in survey_report.auxiliary_machinery.filter(m_am_outer_bullet__exact=br):
                    inner_bullet_in.append(inner.m_am_inner_bullet)
                    inner_bullet_in_rating.append(inner.m_am_rating)
                m_am_inner_bullet.append(inner_bullet_in)
                m_am_rating.append(inner_bullet_in_rating)
                
            
            machinary_image_arr = []
            for gimg in survey_report.machinary_image.all():
                machinary_image_arr.append(str(GlobalConfiguration.get_as_base64(str(gimg.machinary_image)))[2:-1])

            return JsonResponse({
                'code':'200',
                'updated_on':str(survey_report.updated_on).replace('T', ' ')[:19] if survey_report.updated_on else str(now).replace('T', ' ')[:19],
                'm_mpm_description':m_mpm_description,
                'm_mpm_condition_rating':m_mpm_condition_rating,
                'm_mpm_condition':m_mpm_condition,
                'm_eo_description':m_eo_description,
                'm_eo_condition_rating':m_eo_condition_rating,
                'm_se_description':m_se_description,
                'm_se_condition_rating':m_se_condition_rating,
                'm_am_outer_bullet':m_am_outer_bullet,
                'm_am_inner_bullet':m_am_inner_bullet,
                'm_am_rating':m_am_rating,
                'machinary_image':machinary_image,
                'gd_extra_note':survey_report.gd_extra_note
            })
        else:
            
            survey_report.m_mpm_description = request.POST['m_mpm_description']
            survey_report.m_mpm_condition_rating = request.POST['m_mpm_condition_rating']
            survey_report.m_mpm_condition = request.POST['m_mpm_condition']
            survey_report.m_eo_description = request.POST['m_eo_description']
            survey_report.m_eo_condition_rating = request.POST['m_eo_condition_rating']
            survey_report.m_se_description = request.POST['m_se_description']
            survey_report.m_se_condition_rating = request.POST['m_se_condition_rating']
            survey_report.gd_extra_note = request.POST['gd_extra_note']
            
            survey_report.auxiliary_machinery.all().delete()
            m_am_outer_bullet = request.POST.get('m_am_outer_bullet')[1:-1]
            m_am_outer_bullet = ast.literal_eval(m_am_outer_bullet.replace("\\",""))
            m_am_inner_bullet = request.POST.get('m_am_inner_bullet')[1:-1]
            m_am_inner_bullet = ast.literal_eval(m_am_inner_bullet.replace("\\",""))
            m_am_rating = request.POST.get('m_am_rating')[1:-1]
            m_am_rating = ast.literal_eval(m_am_rating.replace("\\",""))
            for j, m_am_inner_bullet in enumerate(m_am_inner_bullet):
                for k, val in enumerate(m_am_inner_bullet):
                    auxiliary_machinery = AuxiliaryMachinery.objects.create(
                        m_am_outer_bullet=m_am_outer_bullet[j],
                        m_am_inner_bullet=val,
                        m_am_rating=m_am_rating[j][k],
                    )
                    survey_report.auxiliary_machinery.add(auxiliary_machinery)

            
            img_data = request.POST.get('img_data').replace("[","").replace("]","")
            img_data_arr = img_data.split(",")
            survey_report.machinary_image.all().delete()
            for image_data in img_data_arr:
                url = GlobalConfiguration.api_b64_aws_s3_image_post("machinary_images/",image_data)
                fnd_images = MachinaryImage.objects.create(
                    machinary_image=url
                )
                survey_report.machinary_image.add(fnd_images)

            survey_report.updated_on = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            survey_report.save()
            return JsonResponse({
                'code':'300'
            })


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step13_image(request):
    file_name = "machinary_images/"+str(uuid.uuid4())+".jpg"
    image_data = request.POST.get('image_data')
    
    #image_data += "==" * ((4 - len(image_data) % 4) % 4)
    image_data = image_data.replace(" ","+")
    session = boto3.session.Session(aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_KEY)
    s3 = session.resource('s3')
    s3.Bucket("dls2018").put_object(Key=file_name, Body=base64.b64decode(image_data), ContentType='image/jpeg', ACL='public-read')
    url = settings.AWS_S3_URL+file_name

    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
    fnd_images = MachinaryImage.objects.create(
        machinary_image=str(url),
        machinary_image_caption=''
    )
    survey_report.machinary_image.add(fnd_images)
    return JsonResponse({"code": str(url)})


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step14(request):
    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))

    survey_report.sed_description = request.POST['sed_description']
    survey_report.cod_description = request.POST['cod_description']
    survey_report.service_description = request.POST['service_description']
    survey_report.hull_condition_rating = request.POST['hull_condition_rating']
    survey_report.loc_dat_survey = request.POST['loc_dat_survey']
    survey_report.hull_condition = request.POST['hull_condition']
    survey_report.gd_extra_note = request.POST['gd_extra_note']


    survey_report.recommendations.all().delete()
    recom_outer_bullet = request.POST.get('recom_outer_bullet')[1:-1]
    recom_outer_bullet = ast.literal_eval(recom_outer_bullet.replace("\\",""))
    recom_inner_bullet = request.POST.get('recom_inner_bullet')[1:-1]
    recom_inner_bullet = ast.literal_eval(recom_inner_bullet.replace("\\",""))
    for j, recom_inner_bullet in enumerate(recom_inner_bullet):
        for k, val in enumerate(recom_inner_bullet):
            recommendations = Recommendations.objects.create(
                recom_outer_bullet=recom_outer_bullet[j],
                recom_inner_bullet=val,
            )
            survey_report.recommendations.add(recommendations)

    
    #please dont remove for update survey complete -siddhartha-12-10-2018
    assign_vessel_details = AssignVessel.objects.get(pk=int(survey_report.assigned_vessel_id))
    assign_vessel_details.survey_complate = datetime.now()
    if assign_vessel_details.stage_completed_id == 4:
        assign_vessel_details.stage_completed_id = 5
    assign_vessel_details.save()


    survey_report.save()
    return HttpResponse(json.dumps({'survey_report_id': str(survey_report.id)}))



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step14_details(request):
    survey_report = None
    now = datetime.now() + timedelta(hours=1)
    sed_description = ''
    cod_description = ''
    service_description = ''
    hull_condition_rating = ''
    loc_dat_survey = ''
    hull_condition = ''
    recom_outer_bullet = []
    recom_inner_bullet = []
    if request.POST['survey_report_id']:
        survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
        
        request_time = 0
        if request.POST['updated_on'] != '0':
            dt = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            request_time = int(time.mktime(dt.timetuple()))
        if time.mktime(survey_report.updated_on.timetuple() if survey_report.updated_on else now.timetuple()) > request_time:
                    
            sed_description = survey_report.sed_description
            cod_description = survey_report.cod_description
            service_description = survey_report.service_description
            hull_condition_rating = survey_report.hull_condition_rating
            loc_dat_survey = survey_report.loc_dat_survey
            hull_condition = survey_report.hull_condition


            for br in survey_report.recommendations.values_list('recom_outer_bullet', flat=True).distinct():
                recom_outer_bullet.append(br)
                inner_bullet_in = []
                for inner in survey_report.recommendations.filter(recom_outer_bullet__exact=br):
                    inner_bullet_in.append(inner.recom_inner_bullet)
                recom_inner_bullet.append(inner_bullet_in)

            
            safety_equipment_image_arr = []
            for gimg in survey_report.safety_equipment_image.all():
                safety_equipment_image_arr.append(str(GlobalConfiguration.get_as_base64(str(gimg.safety_equipment_image)))[2:-1])

            return JsonResponse({
                'code':'200',
                'updated_on':str(survey_report.updated_on).replace('T', ' ')[:19] if survey_report.updated_on else str(now).replace('T', ' ')[:19],
                'sed_description':sed_description,
                'cod_description':cod_description,
                'service_description':service_description,
                'hull_condition_rating':hull_condition_rating,
                'loc_dat_survey':loc_dat_survey,
                'hull_condition':hull_condition,
                'recom_outer_bullet':recom_outer_bullet,
                'recom_inner_bullet':recom_inner_bullet,
                'safety_equipment_image':safety_equipment_image,
                'gd_extra_note':survey_report.gd_extra_note
            })
        else:
                    
            survey_report.sed_description = request.POST['sed_description']
            survey_report.cod_description = request.POST['cod_description']
            survey_report.service_description = request.POST['service_description']
            survey_report.hull_condition_rating = request.POST['hull_condition_rating']
            survey_report.loc_dat_survey = request.POST['loc_dat_survey']
            survey_report.hull_condition = request.POST['hull_condition']
            survey_report.gd_extra_note = request.POST['gd_extra_note']


            survey_report.recommendations.all().delete()
            recom_outer_bullet = request.POST.get('recom_outer_bullet')[1:-1]
            recom_outer_bullet = ast.literal_eval(recom_outer_bullet.replace("\\",""))
            recom_inner_bullet = request.POST.get('recom_inner_bullet')[1:-1]
            recom_inner_bullet = ast.literal_eval(recom_inner_bullet.replace("\\",""))
            for j, recom_inner_bullet in enumerate(recom_inner_bullet):
                for k, val in enumerate(recom_inner_bullet):
                    recommendations = Recommendations.objects.create(
                        recom_outer_bullet=recom_outer_bullet[j],
                        recom_inner_bullet=val,
                    )
                    survey_report.recommendations.add(recommendations)


            img_data = request.POST.get('img_data').replace("[","").replace("]","")
            img_data_arr = img_data.split(",")
            survey_report.safety_equipment_image.all().delete()
            for image_data in img_data_arr:
                url = GlobalConfiguration.api_b64_aws_s3_image_post("safety_equipment_images/",image_data)
                fnd_images = SafetyEquipmentImage.objects.create(
                    safety_equipment_image=url
                )
                survey_report.safety_equipment_image.add(fnd_images)
            
            survey_report.updated_on = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            survey_report.save()
            return JsonResponse({
                'code':'300'
            })



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_step14_image(request):
    file_name = "safety_equipment_images/"+str(uuid.uuid4())+".jpg"
    image_data = request.POST.get('image_data')
    
    #image_data += "==" * ((4 - len(image_data) % 4) % 4)
    image_data = image_data.replace(" ","+")
    session = boto3.session.Session(aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_KEY)
    s3 = session.resource('s3')
    s3.Bucket("dls2018").put_object(Key=file_name, Body=base64.b64decode(image_data), ContentType='image/jpeg', ACL='public-read')
    url = settings.AWS_S3_URL+file_name

    survey_report = SurveyReport.objects.get(pk=int(request.POST['survey_report_id']))
    fnd_images = SafetyEquipmentImage.objects.create(
        safety_equipment_image=str(url),
        safety_equipment_image_caption=''
    )
    survey_report.safety_equipment_image.add(fnd_images)
    return JsonResponse({"code": str(url)})


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_barge_step1(request):
    survey_report_barge=None
    if request.POST['survey_report_id']!='0':
        survey_report_barge = SurveyReportBarge.objects.get(pk=int(request.POST['survey_report_id']))

        survey_report_barge.survey_b_location = request.POST['survey_b_location']
        survey_report_barge.survey_b_location_other = request.POST['survey_b_location_other']
        survey_report_barge.barge_type = request.POST['barge_type']
        survey_report_barge.cargo_covers_num = request.POST['cargo_covers_num']
        survey_report_barge.cargo_covers_type = request.POST['cargo_covers_type']
        survey_report_barge.wing_compartments = request.POST['wing_compartments']
        survey_report_barge.void_bow_compartments = request.POST['void_bow_compartments']
        survey_report_barge.void_stern_compartments = request.POST['void_stern_compartments']
        survey_report_barge.barg_dimentions_length = request.POST['barg_dimentions_length']
        survey_report_barge.barg_dimentions_width = request.POST['barg_dimentions_width']
        survey_report_barge.barg_dimentions_height = request.POST['barg_dimentions_height']
        survey_report_barge.barge_coaming_num = request.POST['barge_coaming_num']
        survey_report_barge.barge_covers_cat = request.POST['barge_covers_cat']
        survey_report_barge.barge_covers_cat_other = request.POST['barge_covers_cat_other']
        survey_report_barge.b_gd_extra_note = request.POST['b_gd_extra_note']

        survey_report_barge.save()
    else:
        survey_report_barge = SurveyReportBarge.objects.create(
            assignment=AssignVessel.objects.get(pk=int(request.POST['assign_vessel_id'])).assignment,
            assigned_vessel=AssignVessel.objects.get(pk=int(request.POST['assign_vessel_id'])),
            created_on=timezone.now(),
            survey_b_location=request.POST['survey_b_location'],
            survey_b_location_other=request.POST['survey_b_location_other'],
            barge_type=request.POST['barge_type'],
            cargo_covers_num=request.POST['cargo_covers_num'],
            cargo_covers_type=request.POST['cargo_covers_type'],
            wing_compartments=request.POST['wing_compartments'],
            void_bow_compartments=request.POST['void_bow_compartments'],
            void_stern_compartments=request.POST['void_stern_compartments'],
            barg_dimentions_length=request.POST['barg_dimentions_length'],
            barg_dimentions_width=request.POST['barg_dimentions_width'],
            barg_dimentions_height=request.POST['barg_dimentions_height'],
            barge_coaming_num=request.POST['barge_coaming_num'],
            barge_covers_cat=request.POST['barge_covers_cat'],
            barge_covers_cat_other=request.POST['barge_covers_cat_other'],
            b_gd_extra_note=request.POST['b_gd_extra_note']
        )
        
    return JsonResponse({"survey_report_id": str(survey_report_barge.id)})



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_barge_step1_details(request):
    survey_report_barge = None
    now = datetime.now() + timedelta(hours=1)

    if request.POST['survey_report_id']:
        survey_report_barge = SurveyReportBarge.objects.get(pk=int(request.POST['survey_report_id']))
        
        request_time = 0
        if request.POST['updated_on'] != '0':
            dt = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            request_time = int(time.mktime(dt.timetuple()))
        if time.mktime(survey_report_barge.updated_on.timetuple() if survey_report_barge.updated_on else now.timetuple()) > request_time:

            data = {
                'survey_b_location':survey_report_barge.survey_b_location,
                'survey_b_location_other':survey_report_barge.survey_b_location_other,
                'barge_type':survey_report_barge.barge_type,
                'cargo_covers_num':survey_report_barge.cargo_covers_num,
                'cargo_covers_type':survey_report_barge.cargo_covers_type,
                'wing_compartments':survey_report_barge.wing_compartments,
                'void_bow_compartments':survey_report_barge.void_bow_compartments,
                'void_stern_compartments':survey_report_barge.void_stern_compartments,
                'barg_dimentions_length':survey_report_barge.barg_dimentions_length,
                'barg_dimentions_width':survey_report_barge.barg_dimentions_width,
                'barg_dimentions_height':survey_report_barge.barg_dimentions_height,
                'barge_coaming_num':survey_report_barge.barge_coaming_num,
                'barge_covers_cat':survey_report_barge.barge_covers_cat,
                'barge_covers_cat_other':survey_report_barge.barge_covers_cat_other,
                'b_gd_extra_note':survey_report_barge.b_gd_extra_note
            }
            

            return JsonResponse({
                'code':'200',
                'updated_on':str(survey_report_barge.updated_on).replace('T', ' ')[:19] if survey_report_barge.updated_on else str(now).replace('T', ' ')[:19],
                'data':data
            })
        else:
                
            survey_report_barge.survey_b_location = request.POST['survey_b_location']
            survey_report_barge.survey_b_location_other = request.POST['survey_b_location_other']
            survey_report_barge.barge_type = request.POST['barge_type']
            survey_report_barge.cargo_covers_num = request.POST['cargo_covers_num']
            survey_report_barge.cargo_covers_type = request.POST['cargo_covers_type']
            survey_report_barge.wing_compartments = request.POST['wing_compartments']
            survey_report_barge.void_bow_compartments = request.POST['void_bow_compartments']
            survey_report_barge.void_stern_compartments = request.POST['void_stern_compartments']
            survey_report_barge.barg_dimentions_length = request.POST['barg_dimentions_length']
            survey_report_barge.barg_dimentions_width = request.POST['barg_dimentions_width']
            survey_report_barge.barg_dimentions_height = request.POST['barg_dimentions_height']
            survey_report_barge.barge_coaming_num = request.POST['barge_coaming_num']
            survey_report_barge.barge_covers_cat = request.POST['barge_covers_cat']
            survey_report_barge.barge_covers_cat_other = request.POST['barge_covers_cat_other']
            survey_report_barge.b_gd_extra_note = request.POST['b_gd_extra_note']

            survey_report_barge.updated_on = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            survey_report_barge.save()
            return JsonResponse({
                'code':'300'
            })
    else:
        survey_report_barge = SurveyReportBarge.objects.create(
            assignment=AssignVessel.objects.get(pk=int(request.POST['assign_vessel_id'])).assignment,
            assigned_vessel=AssignVessel.objects.get(pk=int(request.POST['assign_vessel_id'])),
            created_on=timezone.now(),
            survey_b_location=request.POST['survey_b_location'],
            survey_b_location_other=request.POST['survey_b_location_other'],
            barge_type=request.POST['barge_type'],
            cargo_covers_num=request.POST['cargo_covers_num'],
            cargo_covers_type=request.POST['cargo_covers_type'],
            wing_compartments=request.POST['wing_compartments'],
            void_bow_compartments=request.POST['void_bow_compartments'],
            void_stern_compartments=request.POST['void_stern_compartments'],
            barg_dimentions_length=request.POST['barg_dimentions_length'],
            barg_dimentions_width=request.POST['barg_dimentions_width'],
            barg_dimentions_height=request.POST['barg_dimentions_height'],
            barge_coaming_num=request.POST['barge_coaming_num'],
            barge_covers_cat=request.POST['barge_covers_cat'],
            barge_covers_cat_other=request.POST['barge_covers_cat_other'],
            b_gd_extra_note=request.POST['b_gd_extra_note'],
        )

        return JsonResponse({
            'code':'300',
            "survey_report_id": str(survey_report_barge.id)
        })
        


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_barge_step2(request):
    survey_report_barge = SurveyReportBarge.objects.get(pk=int(request.POST['survey_report_id']))

    survey_report_barge.b_coaming = request.POST['b_coaming']
    survey_report_barge.b_coaming_other = request.POST['b_coaming_other']
    survey_report_barge.b_hopper = request.POST['b_hopper']
    survey_report_barge.b_hopper_other = request.POST['b_hopper_other']
    survey_report_barge.b_covers = request.POST['b_covers']
    survey_report_barge.b_covers_other = request.POST['b_covers_other']
    survey_report_barge.b_cover_rec = request.POST['b_cover_rec']
    survey_report_barge.b_cover_rec_other = request.POST['b_cover_rec_other']
    survey_report_barge.b_deck_fittings = request.POST['b_deck_fittings']
    survey_report_barge.b_deck_fittings_other = request.POST['b_deck_fittings_other']
    survey_report_barge.b_coatings = request.POST['b_coatings']
    survey_report_barge.b_coatings_other = request.POST['b_coatings_other']
    survey_report_barge.b_final_statement = request.POST['b_final_statement']
    survey_report_barge.b_gd_extra_note = request.POST['b_gd_extra_note']
    
    survey_report_barge.bow_compartment.all().delete()

    
    
    bce_hull_condition = GlobalConfiguration.str_replace(request.POST.get('bce_hull_condition')).split(',') if request.POST.get('bce_hull_condition') else ''
    bc_compartment = GlobalConfiguration.str_replace(request.POST.get('bc_compartment')).split(',') if request.POST.get('bc_compartment') else ''
    bc_comp_fow = GlobalConfiguration.str_replace(request.POST.get('bc_comp_fow')).split(',') if request.POST.get('bc_comp_fow') else ''
    bc_check = GlobalConfiguration.str_replace(request.POST.get('bc_check')).split(',') if request.POST.get('bc_check') else ''
    bc_other_condition = GlobalConfiguration.str_replace(request.POST.get('bc_other_condition')).split(',') if request.POST.get('bc_other_condition') else ''
    for i, x in enumerate(bce_hull_condition):
        if x != '':
            bow_compartment = BowCompartment.objects.create(
                bce_hull_condition=bce_hull_condition[i] if i < len(bce_hull_condition) else '',
                bc_compartment=bc_compartment[i] if i < len(bc_compartment)  else '',
                bc_comp_fow=bc_comp_fow[i] if i < len(bc_comp_fow)  else '',
                bc_check='Recommend pump and check compartment' if i < len(bc_check) and str(bc_check[i]) == "true" else '',
                bc_other_condition=bc_other_condition[i] if i < len(bc_other_condition) else '',
            )
            survey_report_barge.bow_compartment.add(bow_compartment)
    

    survey_report_barge.starboard_side.all().delete()
    ss_hull_condition = GlobalConfiguration.str_replace(request.POST.get('ss_hull_condition')).split(',') if request.POST.get('ss_hull_condition') else ''
    ss_compartment = GlobalConfiguration.str_replace(request.POST.get('ss_compartment')).split(',') if request.POST.get('ss_compartment') else ''
    ss_comp_fow = GlobalConfiguration.str_replace(request.POST.get('ss_comp_fow')).split(',') if request.POST.get('ss_comp_fow') else ''
    ss_check = GlobalConfiguration.str_replace(request.POST.get('ss_check')).split(',') if request.POST.get('ss_check') else ''
    ss_other_condition = GlobalConfiguration.str_replace(request.POST.get('ss_other_condition')).split(',') if request.POST.get('ss_other_condition') else ''
    for i, x in enumerate(ss_hull_condition):
        if x != '':
            starboard_side = StarboardSide.objects.create(
                ss_hull_condition=ss_hull_condition[i] if i < len(ss_hull_condition)  else '',
                ss_compartment=ss_compartment[i] if i < len(ss_compartment) else '',
                ss_comp_fow=ss_comp_fow[i] if i < len(ss_comp_fow)  else '',
                ss_check='Recommend pump and check compartment' if i < len(ss_check) and str(ss_check[i]) == "true" else '',
                ss_other_condition=ss_other_condition[i] if i < len(ss_other_condition)  else '',
            )
            survey_report_barge.starboard_side.add(starboard_side)


    survey_report_barge.stern_compartment.all().delete()
    sce_hull_condition = GlobalConfiguration.str_replace(request.POST.get('sce_hull_condition')).split(',') if request.POST.get('sce_hull_condition') else ''
    sc_compartment = GlobalConfiguration.str_replace(request.POST.get('sc_compartment')).split(',') if request.POST.get('sc_compartment') else ''
    sc_comp_fow = GlobalConfiguration.str_replace(request.POST.get('sc_comp_fow')).split(',') if request.POST.get('sc_comp_fow') else ''
    sc_check = GlobalConfiguration.str_replace(request.POST.get('sc_check')).split(',') if request.POST.get('sc_check') else ''
    sc_other_condition = GlobalConfiguration.str_replace(request.POST.get('sc_other_condition')).split(',') if request.POST.get('sc_other_condition') else ''
    for i, x in enumerate(sce_hull_condition):
        if x != '':
            stern_compartment = SternCompartment.objects.create(
                sce_hull_condition=sce_hull_condition[i] if i < len(sce_hull_condition) else '',
                sc_compartment=sc_compartment[i] if i < len(sc_compartment) else '',
                sc_comp_fow=sc_comp_fow[i] if i < len(sc_comp_fow) else '',
                sc_check='Recommend pump and check compartment' if i < len(sc_check) and str(sc_check[i]) == "true" else '',
                sc_other_condition=sc_other_condition[i] if i < len(sc_other_condition) else '',
            )
            survey_report_barge.stern_compartment.add(stern_compartment)


    survey_report_barge.port_side.all().delete()
    ps_hull_condition = GlobalConfiguration.str_replace(request.POST.get('ps_hull_condition')).split(',') if request.POST.get('ps_hull_condition') else ''
    ps_compartment = GlobalConfiguration.str_replace(request.POST.get('ps_compartment')).split(',') if request.POST.get('ps_compartment') else ''
    ps_comp_fow = GlobalConfiguration.str_replace(request.POST.get('ps_comp_fow')).split(',') if request.POST.get('ps_comp_fow') else ''
    ps_check = GlobalConfiguration.str_replace(request.POST.get('ps_check')).split(',') if request.POST.get('ps_check') else ''
    ps_other_condition = GlobalConfiguration.str_replace(request.POST.get('ps_other_condition')).split(',') if request.POST.get('ps_other_condition') else ''
    for i, x in enumerate(ps_hull_condition):
        if x != '':
            port_side = PortSide.objects.create(
                ps_hull_condition=ps_hull_condition[i] if i < len(ps_hull_condition) else '',
                ps_compartment=ps_compartment[i] if i < len(ps_compartment) else '',
                ps_comp_fow=ps_comp_fow[i] if i < len(ps_comp_fow) else '',
                ps_check='Recommend pump and check compartment' if i < len(ps_check) and str(ps_check[i]) == "true" else '',
                ps_other_condition=ps_other_condition[i] if i < len(ps_other_condition) else '',
            )
            survey_report_barge.port_side.add(port_side)

    

    #please dont remove for update survey complete -siddhartha-12-10-2018
    assign_vessel_details = AssignVessel.objects.get(pk=int(survey_report_barge.assigned_vessel_id))
    assign_vessel_details.survey_complate = datetime.now()
    if assign_vessel_details.stage_completed_id == 4:
        assign_vessel_details.stage_completed_id = 5
    assign_vessel_details.save()

    survey_report_barge.save()

    return JsonResponse({"survey_report_id": str(survey_report_barge.id)})



@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_report_barge_step2_details(request):
    survey_report_barge = None
    now = datetime.now() + timedelta(hours=1)

    if request.POST['survey_report_id']:
        survey_report_barge = SurveyReportBarge.objects.get(pk=int(request.POST['survey_report_id']))
        
        request_time = 0
        if request.POST['updated_on'] != '0':
            dt = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            request_time = int(time.mktime(dt.timetuple()))
        if time.mktime(survey_report_barge.updated_on.timetuple() if survey_report_barge.updated_on else now.timetuple()) > request_time:

                    
            b_coaming = survey_report_barge.b_coaming
            b_coaming_other = survey_report_barge.b_coaming_other
            b_hopper = survey_report_barge.b_hopper
            b_hopper_other = survey_report_barge.b_hopper_other
            b_covers = survey_report_barge.b_covers
            b_covers_other = survey_report_barge.b_covers_other
            b_cover_rec = survey_report_barge.b_cover_rec
            b_cover_rec_other = survey_report_barge.b_cover_rec_other
            b_deck_fittings = survey_report_barge.b_deck_fittings
            b_deck_fittings_other = survey_report_barge.b_deck_fittings_other
            b_coatings = survey_report_barge.b_coatings
            b_coatings_other = survey_report_barge.b_coatings_other
            b_final_statement = survey_report_barge.b_final_statement

            bce_hull_condition = []
            bc_compartment = []
            bc_comp_fow = []
            bc_check = []
            bc_other_condition = []
            for hc in survey_report_barge.bow_compartment.all():
                bce_hull_condition.append(hc.bce_hull_condition)
                bc_compartment.append(hc.bc_compartment)
                bc_comp_fow.append(hc.bc_comp_fow)
                bc_check.append('true' if hc.bc_check else 'false')
                bc_other_condition.append(hc.bc_other_condition)
            
            ss_hull_condition = []
            ss_compartment = []
            ss_comp_fow = []
            ss_check = []
            ss_other_condition = []
            for hc in survey_report_barge.starboard_side.all():
                ss_hull_condition.append(hc.ss_hull_condition)
                ss_compartment.append(hc.ss_compartment)
                ss_comp_fow.append(hc.ss_comp_fow)
                ss_check.append('true' if hc.ss_check else 'false')
                ss_other_condition.append(hc.ss_other_condition)

            sce_hull_condition = []
            sc_compartment = []
            sc_comp_fow = []
            sc_check = []
            sc_other_condition = []
            for hc in survey_report_barge.stern_compartment.all():
                sce_hull_condition.append(hc.sce_hull_condition)
                sc_compartment.append(hc.sc_compartment)
                sc_comp_fow.append(hc.sc_comp_fow)
                sc_check.append('true' if hc.sc_check else 'false')
                sc_other_condition.append(hc.sc_other_condition)

            ps_hull_condition = []
            ps_compartment = []
            ps_comp_fow = []
            ps_check = []
            ps_other_condition = []
            for hc in survey_report_barge.port_side.all():
                ps_hull_condition.append(hc.ps_hull_condition)
                ps_compartment.append(hc.ps_compartment)
                ps_comp_fow.append(hc.ps_comp_fow)
                ps_check.append('true' if hc.ps_check else 'false')
                ps_other_condition.append(hc.ps_other_condition)

                    
            return JsonResponse({
                'code':'200',
                'updated_on':str(survey_report_barge.updated_on).replace('T', ' ')[:19] if survey_report_barge.updated_on else str(now).replace('T', ' ')[:19],
                'b_coaming':b_coaming,
                'b_coaming_other':b_coaming_other,
                'b_hopper':b_hopper,
                'b_hopper_other':b_hopper_other,
                'b_covers':b_covers,
                'b_covers_other':b_covers_other,
                'b_cover_rec':b_cover_rec,
                'b_cover_check':'true' if b_cover_rec else 'false',
                'b_cover_rec_other':b_cover_rec_other,
                'b_deck_fittings':b_deck_fittings,
                'b_deck_fittings_other':b_deck_fittings_other,
                'b_coatings':b_coatings,
                'b_coatings_other':b_coatings_other,
                'b_final_statement':b_final_statement,
                'bce_hull_condition':bce_hull_condition,
                'bc_compartment':bc_compartment,
                'bc_comp_fow':bc_comp_fow,
                'bc_check':bc_check,
                'bc_other_condition':bc_other_condition,
                'ss_hull_condition':ss_hull_condition,
                'ss_compartment':ss_compartment,
                'ss_comp_fow':ss_comp_fow,
                'ss_check':ss_check,
                'ss_other_condition':ss_other_condition,
                'sce_hull_condition':sce_hull_condition,
                'sc_compartment':sc_compartment,
                'sc_comp_fow':sc_comp_fow,
                'sc_check':sc_check,
                'sc_other_condition':sc_other_condition,
                'ps_hull_condition':ps_hull_condition,
                'ps_compartment':ps_compartment,
                'ps_comp_fow':ps_comp_fow,
                'ps_check':ps_check,
                'ps_other_condition':ps_other_condition,
                'b_gd_extra_note':survey_report_barge.b_gd_extra_note
            })
        else:
                        
            survey_report_barge.b_coaming = request.POST['b_coaming']
            survey_report_barge.b_coaming_other = request.POST['b_coaming_other']
            survey_report_barge.b_hopper = request.POST['b_hopper']
            survey_report_barge.b_hopper_other = request.POST['b_hopper_other']
            survey_report_barge.b_covers = request.POST['b_covers']
            survey_report_barge.b_covers_other = request.POST['b_covers_other']
            survey_report_barge.b_cover_rec = request.POST['b_cover_rec']
            survey_report_barge.b_cover_rec_other = request.POST['b_cover_rec_other']
            survey_report_barge.b_deck_fittings = request.POST['b_deck_fittings']
            survey_report_barge.b_deck_fittings_other = request.POST['b_deck_fittings_other']
            survey_report_barge.b_coatings = request.POST['b_coatings']
            survey_report_barge.b_coatings_other = request.POST['b_coatings_other']
            survey_report_barge.b_final_statement = request.POST['b_final_statement']
            survey_report_barge.b_gd_extra_note = request.POST['b_gd_extra_note']
            
            survey_report_barge.bow_compartment.all().delete()
            
            bce_hull_condition = GlobalConfiguration.str_replace(request.POST.get('bce_hull_condition')).split(',') if request.POST.get('bce_hull_condition') else ''
            bc_compartment = GlobalConfiguration.str_replace(request.POST.get('bc_compartment')).split(',') if request.POST.get('bc_compartment') else ''
            bc_comp_fow = GlobalConfiguration.str_replace(request.POST.get('bc_comp_fow')).split(',') if request.POST.get('bc_comp_fow') else ''
            bc_check = GlobalConfiguration.str_replace(request.POST.get('bc_check')).split(',') if request.POST.get('bc_check') else ''
            bc_other_condition = GlobalConfiguration.str_replace(request.POST.get('bc_other_condition')).split(',') if request.POST.get('bc_other_condition') else ''
            for i, x in enumerate(bce_hull_condition):
                if x != '':
                    bow_compartment = BowCompartment.objects.create(
                        bce_hull_condition=bce_hull_condition[i] if i < len(bce_hull_condition) else '',
                        bc_compartment=bc_compartment[i] if i < len(bc_compartment)  else '',
                        bc_comp_fow=bc_comp_fow[i] if i < len(bc_comp_fow)  else '',
                        bc_check='Recommend pump and check compartment' if i < len(bc_check) and str(bc_check[i]) == "true" else '',
                        bc_other_condition=bc_other_condition[i] if i < len(bc_other_condition) else '',
                    )
                    survey_report_barge.bow_compartment.add(bow_compartment)
            

            survey_report_barge.starboard_side.all().delete()
            ss_hull_condition = GlobalConfiguration.str_replace(request.POST.get('ss_hull_condition')).split(',') if request.POST.get('ss_hull_condition') else ''
            ss_compartment = GlobalConfiguration.str_replace(request.POST.get('ss_compartment')).split(',') if request.POST.get('ss_compartment') else ''
            ss_comp_fow = GlobalConfiguration.str_replace(request.POST.get('ss_comp_fow')).split(',') if request.POST.get('ss_comp_fow') else ''
            ss_check = GlobalConfiguration.str_replace(request.POST.get('ss_check')).split(',') if request.POST.get('ss_check') else ''
            ss_other_condition = GlobalConfiguration.str_replace(request.POST.get('ss_other_condition')).split(',') if request.POST.get('ss_other_condition') else ''
            for i, x in enumerate(ss_hull_condition):
                if x != '':
                    starboard_side = StarboardSide.objects.create(
                        ss_hull_condition=ss_hull_condition[i] if i < len(ss_hull_condition)  else '',
                        ss_compartment=ss_compartment[i] if i < len(ss_compartment) else '',
                        ss_comp_fow=ss_comp_fow[i] if i < len(ss_comp_fow)  else '',
                        ss_check='Recommend pump and check compartment' if i < len(ss_check) and str(ss_check[i]) == "true" else '',
                        ss_other_condition=ss_other_condition[i] if i < len(ss_other_condition)  else '',
                    )
                    survey_report_barge.starboard_side.add(starboard_side)


            survey_report_barge.stern_compartment.all().delete()
            sce_hull_condition = GlobalConfiguration.str_replace(request.POST.get('sce_hull_condition')).split(',') if request.POST.get('sce_hull_condition') else ''
            sc_compartment = GlobalConfiguration.str_replace(request.POST.get('sc_compartment')).split(',') if request.POST.get('sc_compartment') else ''
            sc_comp_fow = GlobalConfiguration.str_replace(request.POST.get('sc_comp_fow')).split(',') if request.POST.get('sc_comp_fow') else ''
            sc_check = GlobalConfiguration.str_replace(request.POST.get('sc_check')).split(',') if request.POST.get('sc_check') else ''
            sc_other_condition = GlobalConfiguration.str_replace(request.POST.get('sc_other_condition')).split(',') if request.POST.get('sc_other_condition') else ''
            for i, x in enumerate(sce_hull_condition):
                if x != '':
                    stern_compartment = SternCompartment.objects.create(
                        sce_hull_condition=sce_hull_condition[i] if i < len(sce_hull_condition) else '',
                        sc_compartment=sc_compartment[i] if i < len(sc_compartment) else '',
                        sc_comp_fow=sc_comp_fow[i] if i < len(sc_comp_fow) else '',
                        sc_check='Recommend pump and check compartment' if i < len(sc_check) and str(sc_check[i]) == "true" else '',
                        sc_other_condition=sc_other_condition[i] if i < len(sc_other_condition) else '',
                    )
                    survey_report_barge.stern_compartment.add(stern_compartment)


            survey_report_barge.port_side.all().delete()
            ps_hull_condition = GlobalConfiguration.str_replace(request.POST.get('ps_hull_condition')).split(',') if request.POST.get('ps_hull_condition') else ''
            ps_compartment = GlobalConfiguration.str_replace(request.POST.get('ps_compartment')).split(',') if request.POST.get('ps_compartment') else ''
            ps_comp_fow = GlobalConfiguration.str_replace(request.POST.get('ps_comp_fow')).split(',') if request.POST.get('ps_comp_fow') else ''
            ps_check = GlobalConfiguration.str_replace(request.POST.get('ps_check')).split(',') if request.POST.get('ps_check') else ''
            ps_other_condition = GlobalConfiguration.str_replace(request.POST.get('ps_other_condition')).split(',') if request.POST.get('ps_other_condition') else ''
            for i, x in enumerate(ps_hull_condition):
                if x != '':
                    port_side = PortSide.objects.create(
                        ps_hull_condition=ps_hull_condition[i] if i < len(ps_hull_condition) else '',
                        ps_compartment=ps_compartment[i] if i < len(ps_compartment) else '',
                        ps_comp_fow=ps_comp_fow[i] if i < len(ps_comp_fow) else '',
                        ps_check='Recommend pump and check compartment' if i < len(ps_check) and str(ps_check[i]) == "true" else '',
                        ps_other_condition=ps_other_condition[i] if i < len(ps_other_condition) else '',
                    )
                    survey_report_barge.port_side.add(port_side)


            survey_report_barge.updated_on = datetime.strptime(request.POST['updated_on'], '%Y-%m-%d %H:%M:%S')
            survey_report_barge.save()
            return JsonResponse({
                'code':'300'
            })


@parser_classes((FileUploadParser, MultiPartParser, FormParser,))
@csrf_exempt
def upload_media(request):
    form = TestForm(request.POST, request.FILES)
    if form.is_valid():
        original_name = str(uuid.uuid4())+".wav"
        file_name = "recording/"+original_name
        session = boto3.session.Session(aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_KEY)
        s3 = session.resource('s3')
        s3.Bucket("dls2018").put_object(Key=file_name, Body=form.cleaned_data['ionicfile'], ACL='public-read')
        url = settings.AWS_S3_URL+file_name
        text_to_speech.delay(request.POST.get('survey_report_id'), original_name)
        return JsonResponse({"code": "200"})
    else:
        errors = json.dumps(form.errors)
        return HttpResponse(errors, mimetype='application/json')


#survey acknowledge siddhartha oct-22-2018
@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@csrf_exempt
def survey_acknowledged(request):
    vissel_id = request.POST.get('vissel_id')
    assign_vessel_details = AssignVessel.objects.get(pk=int(vissel_id))
    assign_vessel_details.acknowledged = datetime.now()
    if assign_vessel_details.stage_completed_id == 2:
        assign_vessel_details.stage_completed_id = 3
    assign_vessel_details.save()
    return JsonResponse({
                'code':'200',
                'msg': "acknowledge approve successfully",
            })