<?php

use Acms\Services\SocialLogin\Exceptions\SocialLoginException;
use Acms\Services\SocialLogin\Exceptions\SocialLoginDuplicationException;

class ACMS_GET_Api_Twitter_OAuthLoginCallback extends ACMS_GET
{
    public function get()
    {
        /** @var Acms\Services\SocialLogin\Twitter $twitter */
        $twitter = App::make('twitter-login');

        try {
            $loginType = $twitter->getLoginType();
            $loginBid = $twitter->getLoginBid();
            $loginUid = $twitter->getLoginUid();

            if (empty($loginType) || empty($loginBid)) {
                throw new SocialLoginException();
            }

            if (!$twitter->verifyOAuthToken($this->Get->get('oauth_token'))) {
                throw new SocialLoginException('Invalid OAuth token.');
            }

            [
                'access_token' => $accessToken,
                'access_token_secret' => $accessTokenSecret
            ] = $twitter->obtainAccessToken(
                $this->Get->get('oauth_verifier'),
                $this->Get->get('oauth_token')
            );

            $twitter->setMe($accessToken, $accessTokenSecret);

            switch ($loginType) {
                case 'login':
                    $twitter->login();
                    break;
                case 'signup':
                    $twitter->signup($loginBid);
                    break;
                case 'addition':
                    $twitter->addition($loginUid, $loginBid);
                    break;
            }
        } catch (SocialLoginException $e) {
            $twitter->loginFailed('login=failed');
        } catch (SocialLoginDuplicationException $e) {
            $twitter->loginFailed('auth=double');
        } catch (\Exception $e) {
            $twitter->loginFailed('login=failed');
        } finally {
            // clear session
            $twitter->saveRequestTokens(null, null);
        }
    }
}
