global with sharing class AL_MobileApp_Controller {
    
    global class AL_MobileApp_Controller_Exception extends Exception {}
     
    // 写真登録用 リクエスト
    global class CreateAttachmentRequest {
        @TestVisible global String id { get; private set;} // 登録先の土地のオブジェクトID
        @TestVisible global String photo { get; private set;}   // 写真 Base64エンコードされてる
        @TestVisible global String fname { get; private set;}   // 写真 ファイル名
        @TestVisible global String contentType { get; private set;}   // 写真 C/T
        @TestVisible global String photoType { get; private set;}   // 写真種類
        @TestVisible global Long ms { get; private set;}   //アップした日時(ms)
        @TestVisible global String latitude { get; public set; }        // 緯度
        @TestVisible global String longitude { get; public set; }       // 経度
    }
    
    // 写真登録用 レスポンス
    global class CreateAttachmentResponse {
        global String id { get; private set;}         // 登録した添付ファイル=写真のオブジェクトID
        global Boolean success { get; public set; }
        global String  error { get; public set; }
        public CreateAttachmentResponse() {
            this.id = null;
            this.success = false;
            this.error = null;
        }
    }
    
    @RemoteAction
    global static CreateAttachmentResponse createAttachment(CreateAttachmentRequest req) {
        System.debug('received data: '+req);
        Datetime dt = DateTime.newInstance(req.ms);
        CreateAttachmentResponse res = new CreateAttachmentResponse();
        Savepoint sp = Database.setSavepoint();
        try {
            String objectName = SchemaGlobalDescribe.findObjectNameFromRecordIdPrefix(req.id); //idをもとに、オブジェクトAPI名を取得
            SObject s = Database.query('SELECT Name, ' + req.photoType+'_date1__c FROM ' + objectName + ' where id=\''+req.id+'\'');
            s.put('photoType__c' , req.photoType); //写真種類をセットする
            s.put(req.photoType+'_date__c' , dt); //写真をアップした日時をセットする
            if(s.get(req.photoType + '_date1__c') == null){ //初めてアップロード
            	s.put(req.photoType+'_date1__c' , dt);
            }
            update s;
            
            String extension = req.fname.split('\\.(?=[^\\.]+$)')[1]; //拡張子
            
            ContentVersion v = new ContentVersion();
            v.versionData = EncodingUtil.base64Decode(req.photo);
            v.title = String.valueOf(s.get('Name')) + '_' + req.photoType + '_' + dt.format('yyyyMMddHHmmss')+'.'+extension;
            v.pathOnClient = '/aaaaaa.png';
            insert v;
            
            ContentVersion tmp1 = [select id,latitude__c,longitude__c,ContentDocumentId from ContentVersion where id = :v.id];
	        ContentWorkspace shareWorkspace = [select id from ContentWorkspace where name = 's1_photo' limit 1];
	
	        ContentWorkspaceDoc docLink = new ContentWorkspaceDoc();
	        docLink.ContentDocumentId = tmp1.ContentDocumentId;
	        docLink.ContentWorkspaceId = shareWorkspace.id;
	        insert docLink;
            
            tmp1.latitude__c = req.latitude;
            tmp1.longitude__c = req.longitude;
            update tmp1;
            
            ContentDocumentLink cdl = new ContentDocumentLink(ContentDocumentId = tmp1.ContentDocumentId, LinkedEntityId = req.id,ShareType='V');
            insert cdl;
                 
            Event e = new Event();
            e.StartDateTime = dt;
            e.EndDateTime = dt.addMinutes(15);
            //TODO sunbridge_ga テーブル名（漢字）と req.photoType （漢字） にする可能性が高い 2016.10.20
            e.Subject = '拍摄了'+req.photoType+'的照片';
            e.WS_flg__c = false;
            if(objectName == 'Rental_Apply__c'){
            	Rental_Apply__c ra = [select account__c,account__r.name from Rental_Apply__c where id=:req.id][0];
            	e.Location = ra.account__r.name;
            	e.whatid__c = ra.account__c;
            	//e.Location = [select account__r.name from Rental_Apply__c where id=:req.id][0].account__r.name;
            } else if (objectName == 'Repair__c'){
            	Repair__c rp = [select account__c,account__r.name from Repair__c where id=:req.id][0];
            	e.whatid__c = rp.account__c;
            	e.whatid__c = rp.account__c;
            	//e.Location = [select account__r.name from Repair__c where id=:req.id][0].account__r.name;
            } else if (objectName == 'Asset'){
            	Asset ast = [select account.id,account.name from Asset where id=:req.id][0];
            	e.Location = ast.account.name;
            	e.whatid__c = ast.account.id;
            	//e.Location = [select account.name from Asset where id=:req.id][0].account.name;
            }
            insert e;
            res.id = v.id;
            res.success = true;
        }
        catch (Exception e) {
        	    Database.rollback(sp);
            res.success = false;
            res.error = e.getMessage();
            System.debug(Logginglevel.ERROR, e.getStackTraceString());
        }
        return res;
    }
    
}