Kakao.init("d14ff69914d19edcc7ce7a7f6fee0c86");
console.log("Kakao.isInitialized()");
console.log(Kakao.isInitialized());
function loginWithKakao() {
	if (Kakao.Auth.getAccessToken()) { // 토큰이 존재하면 삭제 
        console.log('토큰 삭제 ');
        Kakao.Auth.logout(function() {
            console.log(Kakao.Auth.getAccessToken());
            console.log("카카오 토큰 삭제후 로그인");
            kakaoLoginAuthorizeTens();
        });
    } else {
        kakaoLoginAuthorizeTens()
   }
}
function kakaoLoginAuthorizeTens(){
    Kakao.Auth.authorize({
            // 초기화한 앱의 로그인 Redirect URI에 등록된 URI여야 합니다.
            redirectUri: 'https://dev1.wekoinonia.org/login/authKakao.php',
            //scope: 'profile account_email  friends talk_message',
            scope: 'profile_nickname profile_image',
            state: getRef()
    	});
}
function getRef()
{
    let next = document.getElementById("next").value;
    if(!next) return document.referrer;

    return next;
}
// 아래는 데모를 위한 UI 코드입니다.
//getToken()
function getToken() {
	const token = getCookie('authorize-access-token')
	if(token) {
		Kakao.Auth.setAccessToken(token)
		document.getElementById('token-result').innerText = 'login success. token: ' + Kakao.Auth.getAccessToken()
	}
}
function getCookie(name) {
	const value = "; " + document.cookie;
	const parts = value.split("; " + name + "=");
	if (parts.length === 2) return parts.pop().split(";").shift();
}
function kakaolink(svcId, form, linkCallback ) {
	Kakao.Auth.login({
		// 초기화한 앱의 로그인 Redirect URI에 등록된 URI여야 합니다.
		  success: function(response) {
			     //console.log(response.access_token);
			     //console.log(response.refresh_token);
			     //console.log(response.token_type);
			     //console.log(response.expires_in);
	    		// alert(JSON.stringify(response));

			    /* 바로 로그인 처리하는 방식 */ 
			    Kakao.API.request({
			    	url: '/v2/user/me',
			    	success: function(res) {
			    		// alert(JSON.stringify(res));
			    		var param = res;
			    		param.site = 'kakao';
		                asyncSubmit(svcId, form , linkCallback, {paramtype: "json", param: param});			    		
			    	},
			    	fail: function(error){
			    		  alert(
			    		            'login success, but failed to request user information: ' +
			    		              JSON.stringify(error)			 );
			    	},
			  });
			  


		      },
		fail: function(error) {
			    console.log(error);
	    		alert("로그인 처리 못했습니다\n" + JSON.stringify(response));

		},
    });
}

// 연결끊기 
function kakaounlink() {
    console.log("Kakao.Auth.getAccessToken() = ",Kakao.Auth.getAccessToken());
    if (!Kakao.Auth.getAccessToken()) {
                console.log('Not logged in.');
                const token = getCookie('authorize-access-token')
	            if(token) {
		            Kakao.Auth.setAccessToken(token)
                }
                //Kakao.Auth.setAccessToken("");            
            }
 
    Kakao.API.request({
			    	url: '/v1/user/unlink',
			    	success: function(res) {
			    		alert(JSON.stringify(res));
			    		console.log(res);
			    	},
			    	fail: function(error){
			    		  alert(JSON.stringify(error)			 );
			    	}
    });
    
}

function kakaolinkInvite(thisUrl,thisTitle,userList){
    console.log(">>>>>>>>>" + thisUrl);
    //Kakao.Link.sendScrap({
    //   requestUrl: thisUrl,
    //   installTalk: true
    //});
    Kakao.Link.sendDefault({
      objectType: 'feed',
      content: {
        title: thisTitle,
        description: "참석자 : " + userList,
        imageUrl: "https://k.kakaocdn.net/14/dn/btqFvuVOuAy/p0SNizdk0YH0e0r1WyG9M0/o.jpg",
        link: {
          mobileWebUrl: thisUrl,
          webUrl: thisUrl,
        },
      },
      social: {
        likeCount: 0,
        commentCount: 0,
        sharedCount: 0,
      },
      buttons: [
        {
          title: '웹으로 보기',
          link: {
            mobileWebUrl: thisUrl,
            webUrl:thisUrl,
          },
        },
        // {
        //  title: '앱으로 보기',
        //  link: {
        //    mobileWebUrl: 'https://developers.kakao.com',
        //    webUrl: 'https://developers.kakao.com',
        //  },
        //},
      ],
    })
}
function kakaoTestInvite(thisUrl,thisTitle,thisDescription){
    console.log(">>>>>>>>>" + thisUrl);
    //Kakao.Link.sendScrap({
    //   requestUrl: thisUrl,
    //   installTalk: true
    //});
    Kakao.Link.sendDefault({
      objectType: 'feed',
      content: {
        title: thisTitle,
        description: thisDescription,
        imageUrl: "https://k.kakaocdn.net/14/dn/btqFvuVOuAy/p0SNizdk0YH0e0r1WyG9M0/o.jpg",
        link: {
          mobileWebUrl: thisUrl,
          webUrl: thisUrl,
        },
      },
      social: {
        likeCount: 0,
        commentCount: 0,
        sharedCount: 0,
      },
      buttons: [
        {
          title: '웹으로 보기',
          link: {
            mobileWebUrl: thisUrl,
            webUrl:thisUrl,
          },
        },
        // {
        //  title: '앱으로 보기',
        //  link: {
        //    mobileWebUrl: 'https://developers.kakao.com',
        //    webUrl: 'https://developers.kakao.com',
        //  },
        //},
      ],
    })
}

// return YYYY-MM-DD
function getToday(){
  var today = new Date();

  var year = today.getFullYear();
  var month = ("0" + (today.getMonth()+1)).slice(-2) ; 
  var day =  ("0" + today.getDate()).slice(-2);

  return year + "-" + month + "-" + day;

}
// return hh:mm:ss
function getCurrentTime(h){
    var d = new Date();
    if(h){
      d.setHours(d.getHours() + h); 
    }
    var hour =("0" +  d.getHours()).slice(-2) ;
    var minute = ("0" + d.getMinutes()).slice(-2) ;
    var second = ("0" +  d.getSeconds()).slice(-2) ;

    //return hour + ":" + minute + ":" + second;
    return hour + ":" + minute ; //+ ":" + second;

}

// return YYYY-MM-DD 
// input date;
function getYYYYMMDD(d){
  var year = d.getFullYear();
  var month = ("0" + (d.getMonth()+1)).slice(-2) ; 
  var day =  ("0" + d.getDate()).slice(-2);

  return year + "-" + month + "-" + day;
}
// return hh:mm:ss
function getHHMM(d){
    var hour =("0" +  d.getHours()).slice(-2) ;
    var minute = ("0" + d.getMinutes()).slice(-2) ;
    var second = ("0" +  d.getSeconds()).slice(-2) ;

    return hour + ":" + minute ; 
}

/*
array(0) {
}
*/