AWSTemplateFormatVersion: 2010-09-09
Description: >
  "Disable Deskphone for agents  in Amazon Connect"

Mappings:
  FunctionMap:
      Configuration:
          S3Bucket: "mytestblog"
          S3Key: "custom-ccp-portal/"



####################################################################################
Parameters:
####################################################################################

Parameters:
#  RegionName:
#    Type: String
#    Description: Region where Ammazon Connect is Running

  CustomCCPS3BucketSourceCode:
    Type: String
    AllowedPattern: '(?=^.{3,63}$)(?!^(\d+\.)+\d+$)(^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])$)'
    ConstraintDescription: 'Invalid S3 Bucket name'
    Description: Enter the (globally unique) name you would like to use for the Amazon S3 bucket where Website source code will be copied from

  CustomCCPS3BucketForWebSite:
    Type: String
    AllowedPattern: '(?=^.{3,63}$)(?!^(\d+\.)+\d+$)(^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])$)'
    ConstraintDescription: 'Invalid S3 Bucket name'
    Description: Enter the (globally unique) name you would like to use for the Amazon S3 bucket where we will store the website assets and the sample contact flow. This template will fail to deploy if the bucket name you chose is currently in use.

  instanceIdParam:
    Type: String
    AllowedPattern: '\w{8}-\w{4}-\w{4}-\w{4}-\w{12}'
    ConstraintDescription: "Invalid Amazon Connect instance Id"
    Description: Amazon Connect Instance ID (Ensure you it is entered accurately in the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx). Must be in this account and same region where this stack is.

  instanceNameParam:
    Type: String
    ConstraintDescription: "Invalid Amazon Connect instance alias"
    Description: Amazon Connect Instance Alias (Ensure you it is entered accurately as configured under Amazon Connect Service ).


Outputs:
  CloudfrontEndpoint:
    Description: Endpoint for Cloudfront distribution
    Value: !Join
      - ''
      - - 'https://'
        - !GetAtt [CustomCCPCloudFrontDistribution, DomainName]
        - '/agentDesktop.html'

####################################################################################
Resources:
####################################################################################

Resources:

  CloudWatchRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - apigateway.amazonaws.com
            Action: 'sts:AssumeRole'
      Path: /
      ManagedPolicyArns:
        - >-
          arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs
  Account:
    Type: 'AWS::ApiGateway::Account'
    Properties:
      CloudWatchRoleArn: !GetAtt
        - CloudWatchRole
        - Arn

  createWebSiteS3Bucket:
      Type: 'AWS::S3::Bucket'
      Properties:
          BucketName: !Ref CustomCCPS3BucketForWebSite
          PublicAccessBlockConfiguration:
              BlockPublicAcls: False
              BlockPublicPolicy: False
              IgnorePublicAcls: False
              RestrictPublicBuckets: False
          WebsiteConfiguration:
              IndexDocument: agentDesktop.html
              ErrorDocument: error.html

  CustomCCPs3BucketPolicy:
      Type: AWS::S3::BucketPolicy
      DependsOn:
          - CustomCCPCloudFrontDistributionAccessIdentity
      Properties:
          Bucket: !Ref createWebSiteS3Bucket
          PolicyDocument:
              Statement:
                  -
                      Action:
                          - "s3:GetObject"
                      Effect: "Allow"
                      Principal:
                          CanonicalUser:
                              Fn::GetAtt: [ CustomCCPCloudFrontDistributionAccessIdentity , S3CanonicalUserId ]
                      Resource:
                          !Sub ${createWebSiteS3Bucket.Arn}/CCP/*

  CustomCCPCloudFrontDistributionAccessIdentity:
      Type: AWS::CloudFront::CloudFrontOriginAccessIdentity
      Properties:
        CloudFrontOriginAccessIdentityConfig:
          Comment: 'CloudFront endpoint for Custom CCP'

  CustomCCPCloudFrontDistribution:
      Type: AWS::CloudFront::Distribution
      Properties:
        DistributionConfig:
          Origins:
          - DomainName:
              !Join
                  - ''
                  - - !Ref CustomCCPS3BucketForWebSite
                    - .s3.amazonaws.com
            Id: !Ref CustomCCPS3BucketForWebSite
            OriginPath: '/CCP'
            S3OriginConfig:
              OriginAccessIdentity:
                  !Join
                      - ''
                      - - 'origin-access-identity/cloudfront/'
                        - !Ref CustomCCPCloudFrontDistributionAccessIdentity
          Enabled: 'true'
          Logging:
              Bucket: !GetAtt createWebSiteS3Bucket.DomainName
              Prefix: 'logs/'
              IncludeCookies: 'true'
          Comment: CloudFront for Custom CCP AdminDesktop
          DefaultRootObject: agentDesktop.html
          DefaultCacheBehavior:
              AllowedMethods:
                  - DELETE
                  - GET
                  - HEAD
                  - OPTIONS
                  - PATCH
                  - POST
                  - PUT
              TargetOriginId: !Ref CustomCCPS3BucketForWebSite
              ForwardedValues:
                  QueryString: true
                  Cookies:
                      Forward: all
              ViewerProtocolPolicy: redirect-to-https
          Restrictions:
              GeoRestriction:
                  RestrictionType: whitelist
                  Locations:
                      - US


  CustomCCPWebSiteCreatorRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          -
            Effect: "Allow"
            Principal:
              Service:
                - "lambda.amazonaws.com"
            Action:
              - "sts:AssumeRole"
      Path: /
      ManagedPolicyArns:
        - !Ref CustomCCPWebSiteCreatorPolicy

  CustomCCPWebSiteCreatorPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      ManagedPolicyName: !Sub ${AWS::StackName}-website-creator-policy
      Path: /
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          -
            Effect: "Allow"
            Action:
              - 'logs:CreateLogGroup'
              - 'logs:CreateLogStream'
              - 'logs:PutLogEvents'
            Resource:
              - !Sub "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*"
          -
            Effect: "Allow"
            Action:
              - "s3:PutObject"
              - "s3:GetObject"
              - "s3:PutObjectAcl"
            Resource:
              -  !Join
                  - ''
                  - - 'arn:'
                    - !Ref 'AWS::Partition'
                    - ':s3:::'
                    - !Ref CustomCCPS3BucketForWebSite
                    - '/*'
          -
            Effect: "Allow"
            Action:
              - "s3:PutBucketPublicAccessBlock"
            Resource:
              -  !Join
                  - ''
                  - - 'arn:'
                    - !Ref 'AWS::Partition'
                    - ':s3:::'
                    - !Ref CustomCCPS3BucketForWebSite
          -
            Effect: "Allow"
            Action:
              - "s3:GetObject"
            Resource:
              -  !Join
                  - ''
                  - - 'arn:'
                    - !Ref 'AWS::Partition'
                    - ':s3:::'
                    - !Ref CustomCCPS3BucketSourceCode
                    - '/*'


  webSiteCreator:
    Type: "AWS::Lambda::Function"
    Properties:
      Description:  >
          AWS Lambda Function that will create the website and upload it to the S3 bucket
      Handler: "index.handler"
      Role: !GetAtt CustomCCPWebSiteCreatorRole.Arn
      Runtime: "nodejs12.x"
      MemorySize: 256
      Timeout: 120
      Code:
          S3Bucket: !Ref CustomCCPS3BucketSourceCode
          S3Key: !Join [ "", ['custom-ccp-portal', '/WebSiteHelper.zip'] ]


  invokeWebSiteCreator:
      Type: Custom::CreateWebSite
      DependsOn: createWebSiteS3Bucket
      Properties:
          ServiceToken:  !GetAtt webSiteCreator.Arn
          customAction: configureWebsite
          Region: !Ref AWS::Region
          sourceS3Bucket: !Ref CustomCCPS3BucketSourceCode
          sourceS3key: "custom-ccp-portal"
          destS3Bucket: !Ref CustomCCPS3BucketForWebSite
          destS3KeyPrefix: CCP
          instanceID: !Ref instanceIdParam
          instanceName: !Ref instanceNameParam
          gatewayAPI: !Ref DisableDeskphoneApi
          manifestLocation: "custom-ccp-portal/web-site-manifest.json"


  agentDataDynamoDBTable:
    Type: AWS::DynamoDB::Table
    Properties:
      AttributeDefinitions:
      - AttributeName: agentID
        AttributeType: S
      KeySchema:
      - AttributeName: agentID
        KeyType: HASH
      BillingMode: PAY_PER_REQUEST



  DeskphoneDisableIsAdmin:
    Type: 'AWS::Lambda::Function'
    Properties:
      Environment:
        Variables:
          TargetConnectInstanceId: !Ref instanceIdParam
      Handler: index.lambda_handler
      Timeout: 30
      Runtime: python3.8
      Role: !GetAtt BlogConnectLambdaRole.Arn
      Code:
        ZipFile: !Sub |
          import boto3
          from botocore.exceptions import ClientError
          import json
          import os

          import logging

          #Define Connect Instance
          client = boto3.client('connect')


          def lambda_handler(event, context):
              print ("event", event)
              try:
                  headers = {"Access-Control-Allow-Headers" : "Content-Type",
                              "Access-Control-Allow-Origin" : "*",
                              "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
                  }
                  InstID = os.environ['TargetConnectInstanceId']

                  body=json.loads(event['body'])

                  inputUserName=body['agentUserName']

                  print ("Username passed is", inputUserName)


                  response = client.list_users(
                      InstanceId=InstID,
                      MaxResults=100)

                  userlist = response['UserSummaryList']

                  userfound=0

                  for agent in userlist:
                      if agent['Username'] == inputUserName :
                          userId=agent['Id']
                          print ("Found User", inputUserName, ":", userId)
                          userfound=1
                          break

                  if userfound !=1:
                      print ("user is not found", inputUserName)
                      return {
                          'statusCode' : 200,
                          "headers": headers,
                          'body': json.dumps({"isAdmin" : "false","error": "Not a valid user"})
                      }


                  response = client.list_security_profiles(
                      InstanceId=InstID,
                      MaxResults=100)


                  securityProfileList = response['SecurityProfileSummaryList']
                  for securityProfile in securityProfileList:
                      if securityProfile['Name'] == 'Admin':
                          adminsecurityProfileId = securityProfile['Id']

                          print ("Admin ID is ", adminsecurityProfileId)



                  response = client.describe_user(UserId = userId,
                      InstanceId=InstID)



                  userInfo = response['User']

                  agentSecurityProfileList  = userInfo['SecurityProfileIds']
                  if adminsecurityProfileId in agentSecurityProfileList:
                      print ("This user is admin")

                      return {
                          'statusCode' : 200,
                          "headers": headers,
                          'body': json.dumps({"isAdmin" : "true"})
                      }

                  else:
                      print ("This user is not Admin")
                      return {
                          'statusCode' : 200,
                          "headers": headers,
                          'body': json.dumps(
                              {
                                  "isAdmin" : "false",
                                  "error" : "This user is not Admin"
                              }
                          )
                      }
              except Exception as e:
                  print (e)
                  return {
                      'statusCode' : 200,
                      "headers": headers,
                      'body': json.dumps(
                          {
                              "isAdmin" : "false",
                              "error" : e
                          }
                      )
                  }


  DeskphoneDisableDeskPhone:
    Type: 'AWS::Lambda::Function'
    Properties:
      Environment:
        Variables:
          TargetConnectInstanceId: !Ref instanceIdParam
          DDBAgentTable: !Select [1, !Split ['/', !GetAtt agentDataDynamoDBTable.Arn]]
      Handler: index.lambda_handler
      Timeout: 30
      Runtime: python3.8
      Role: !GetAtt BlogConnectLambdaRole.Arn
      Code:
        ZipFile: !Sub |
          import boto3
          from botocore.exceptions import ClientError
          import json
          import os

          import logging


          client = boto3.client('connect')

          ddb_table = os.environ['DDBAgentTable']

          def lambda_handler(event, context):
              print("event", event)
              try:

                  headers = {"Access-Control-Allow-Headers" : "Content-Type",
                              "Access-Control-Allow-Origin" : "*",
                              "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
                  }
                  # get all users from Connect Instance
                  InstID = os.environ['TargetConnectInstanceId']

                  response = client.list_users(
                      InstanceId=InstID,
                      MaxResults=100)
                  userlist = response['UserSummaryList']

                  # Get the input user List from the argument

                  body=json.loads(event['body'])

                  inputuserList=body['agentUserNames']

                  resetDeskPhoneStatus = {}

                  for userName in inputuserList:
                      inputUserName=userName

                      print ("Username passed is", inputUserName)

                      userfound=0

                      for agent in userlist:
                          if agent['Username'] == inputUserName :
                              userId=agent['Id']
                              print ("Found User", inputUserName, ":", userId)
                              userfound=1
                              break

                      if userfound !=1:
                          print ("user is not found", inputUserName)

                          resetDeskPhoneStatus.update({inputUserName:"user not found"})

                      if userfound==1:
                          softPhoneConfig={'PhoneType': 'SOFT_PHONE'}


                          userResponse = client.describe_user(UserId = userId,
                              InstanceId=InstID)

                          userInfo = userResponse['User']
                          userPhoneInfo=userResponse['User']['PhoneConfig']['PhoneType']

                          print (userPhoneInfo)
                          #Command to Upmaydate to Softphone
                          if userPhoneInfo == 'DESK_PHONE':
                              response = client.update_user_phone_config(
                                  PhoneConfig=softPhoneConfig,
                                  UserId=userId,
                                  InstanceId=InstID)
                              update_disabled_desk_phone(userId, 'SOFT_PHONE')
                              resetDeskPhoneStatus.update({inputUserName:"success"})
                          else:
                              print ("This user already has SoftPhone")
                              resetDeskPhoneStatus.update({inputUserName:"User already has SoftPhone"})
                  return {
                      'statusCode' : 200,
                      "headers": headers,
                      'body': json.dumps(resetDeskPhoneStatus)
                  }

              except Exception as e:
                  print (e)
                  return {

                      "error" : e
                  }

          def update_disabled_desk_phone(agentId, phoneType, dynamodb=None):
              if not dynamodb:
                  dynamodb = boto3.resource('dynamodb')
              table = dynamodb.Table(ddb_table)
              ddb_response = table.update_item(
                  Key={
                      'agentID': agentId
                  },
                  UpdateExpression="set phoneType=:p",
                  ExpressionAttributeValues={
                      ':p': phoneType
                  },
                  ReturnValues="UPDATED_NEW"
              )
              return ddb_response

  DeskphoneDisableGetAgents:
    Type: 'AWS::Lambda::Function'
    DependsOn: agentDataDynamoDBTable
    Properties:
      Environment:
        Variables:
          DDBAgentTable: !Select [1, !Split ['/', !GetAtt agentDataDynamoDBTable.Arn]]
      Handler: index.lambda_handler
      Timeout: 30
      Role: !GetAtt LambdaBasicExecutionRole.Arn
      Runtime: python3.8
      Role: !GetAtt BlogConnectDDBRole.Arn
      Code:
        ZipFile: !Sub |
          import json
          import boto3
          import os
          from boto3.dynamodb.conditions import Key, Attr

          ddb_table = os.environ['DDBAgentTable']

          def lambda_handler(event, context):

              headers = {"Access-Control-Allow-Headers" : "Content-Type",
                          "Access-Control-Allow-Origin" : "*",
                          "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
              }

              dynamodb = boto3.resource('dynamodb')

              table = dynamodb.Table(ddb_table)

              response =table.scan(
                  FilterExpression=Attr('phoneType').eq('DESK_PHONE')
              )
              result = response['Items']

              print(result)

              return {
                  'statusCode': 200,
                  "headers": headers,
                  'body': json.dumps(result)
              }

  DeskphoneDisableGetAgentInfo:
    Type: 'AWS::Lambda::Function'
    DependsOn: agentDataDynamoDBTable
    Properties:
      Environment:
        Variables:
          TargetConnectInstanceId: !Ref instanceIdParam
          DDBAgentTable: !Select [1, !Split ['/', !GetAtt agentDataDynamoDBTable.Arn]]
      Handler: index.lambda_handler
      Timeout: 30
      Runtime: python3.8
      Role: !GetAtt BlogConnectGetAgentInfoRole.Arn
      Code:
        ZipFile: !Sub |
          import boto3
          from botocore.exceptions import ClientError
          import json
          import logging
          import os

          dynamodb = boto3.resource('dynamodb')

          #Define Connect Instance
          client = boto3.client('connect')

          InstID = os.environ['TargetConnectInstanceId']
          ddb_table = os.environ['DDBAgentTable']

          table = dynamodb.Table(ddb_table)

          def dbInsert(agentID,userName,phoneType):
              response = table.update_item(
                  Key={
                      'agentID':agentID
                  },
                  UpdateExpression="set userName = :userName, phoneType = :phoneType",
                  ExpressionAttributeValues={
                      ':userName': userName,
                      ':phoneType': phoneType,
                  },
              ReturnValues="UPDATED_NEW"
              )

          def lambda_handler(event, context):

              response = client.list_users(
                          InstanceId=InstID,
                          MaxResults=500)
              userlist = response['UserSummaryList']

              userfound=0

              for agent in userlist:
                  print(agent['Username'])
                  userID = agent['Id']
                  agentInfo = client.describe_user(UserId = userID,
                                          InstanceId=InstID)
                  agentDetails = agentInfo['User']
                  print(agentDetails['PhoneConfig']['PhoneType'])
                  userName = agent['Username']
                  phoneType = agentDetails['PhoneConfig']['PhoneType']
                  dbInsert(userID, userName,phoneType)


  BlogConnectLambdaRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
        - !Ref BlogConnectLambdaPolicy

  BlogConnectLambdaPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      ManagedPolicyName: !Sub ${AWS::StackName}-blog-connect-lambda-policy
      Path: /
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - connect:DescribeUser
              - connect:ListUsers
              - connect:UpdateUserPhoneConfig
              - connect:ListSecurityProfiles
              - dynamodb:UpdateItem
            Resource: "*"


  BlogConnectDDBRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
        - !Ref BlogConnectDDBPolicy

  BlogConnectDDBPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      ManagedPolicyName: !Sub ${AWS::StackName}-blog-connect-ddb-policy
      Path: /
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - dynamodb:Scan
              - logs:CreateLogGroup
              - logs:CreateLogStream
              - logs:PutLogEvents
            Resource: "*"

  BlogConnectGetAgentInfoRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
        - !Ref BlogConnecGetAgentInfoPolicy

  BlogConnecGetAgentInfoPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      ManagedPolicyName: !Sub ${AWS::StackName}-blog-connect-get-agent-info-policy
      Path: /
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - dynamodb:UpdateItem
              - logs:CreateLogGroup
              - logs:CreateLogStream
              - logs:PutLogEvents
              - connect:ListUsers
              - connect:DescribeUser
            Resource: "*"

  DisableDeskphoneApi:
    Properties:
      Description: Disable Deskphone API
      EndpointConfiguration:
        Types:
        - EDGE
      FailOnWarnings: true
      Name: DisableDeskphoneApi
      Policy:
        Statement:
        - Action: execute-api:Invoke
          Effect: Allow
          Principal: '*'
          Resource: '*'
        Version: '2012-10-17'
    Type: AWS::ApiGateway::RestApi

  DisableDeskphoneApiResource:
    Type: AWS::ApiGateway::Resource
    Properties:
      ParentId: !GetAtt
        - DisableDeskphoneApi
        - RootResourceId
      PathPart: 'DeskphoneDisable-DisableDeskPhone'
      RestApiId: !Ref DisableDeskphoneApi

  GetAgentsApiResource:
    Type: AWS::ApiGateway::Resource
    Properties:
      ParentId: !GetAtt
        - DisableDeskphoneApi
        - RootResourceId
      PathPart: 'DeskphoneDisable-GetAgents'
      RestApiId: !Ref DisableDeskphoneApi

  IsAdminApiResource:
    Type: AWS::ApiGateway::Resource
    Properties:
      ParentId: !GetAtt
        - DisableDeskphoneApi
        - RootResourceId
      PathPart: 'DeskphoneDisable-IsAdmin'
      RestApiId: !Ref DisableDeskphoneApi

  DisableDeskphoneApiRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
        - Action:
          - sts:AssumeRole
          Effect: Allow
          Principal:
            Service:
            - apigateway.amazonaws.com
        Version: '2012-10-17'
      Path: '/'
      ManagedPolicyArns:
        - !Ref DisableDeskphoneApiLambdaAccess

  DisableDeskphoneApiLambdaAccess:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      ManagedPolicyName: !Sub ${AWS::StackName}-disable-deskphone-api-lambda-access
      Path: /
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Action:
          - lambda:InvokeFunction
          Effect: Allow
          Resource:
            - !GetAtt DeskphoneDisableDeskPhone.Arn
            - !GetAtt DeskphoneDisableIsAdmin.Arn
            - !GetAtt DeskphoneDisableGetAgents.Arn


  DisableDeskphoneApiDeployment:
    DependsOn:
      - DisableDeskphoneApiMethod
      - DeskphoneDisableGetAgentsMethod
      - DeskphoneDisableIsAdminMethod
    Properties:
      RestApiId: !Ref DisableDeskphoneApi
    Type: AWS::ApiGateway::Deployment

  DisableDeskphoneApiMethod:
    Type: AWS::ApiGateway::Method
    DependsOn: DisableDeskphoneApi
    Properties:
      AuthorizationType: NONE
      HttpMethod: POST
      Integration:
        IntegrationHttpMethod: POST
        Credentials: !GetAtt DisableDeskphoneApiRole.Arn
        Type: AWS_PROXY
        Uri:
          Fn::Join:
          - ''
          - - 'arn:aws:apigateway:'
            - Ref: AWS::Region
            - :lambda:path/2015-03-31/functions/
            - Fn::GetAtt:
              - DeskphoneDisableDeskPhone
              - Arn
            - /invocations
        IntegrationResponses:
          - StatusCode: 200
            ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
              method.response.header.Access-Control-Allow-Origin: "'*'"
            ResponseTemplates:
              application/json: ''
        PassthroughBehavior: WHEN_NO_MATCH
        RequestTemplates:
          application/json: '{"statusCode": 200}'
      MethodResponses:
        - ResponseModels:
            application/json: 'Empty'
          ResponseParameters:
            method.response.header.Access-Control-Allow-Headers: true
            method.response.header.Access-Control-Allow-Methods: true
            method.response.header.Access-Control-Allow-Origin: true
          StatusCode: 200
      ResourceId: !Ref DisableDeskphoneApiResource
      RestApiId: !Ref DisableDeskphoneApi

  DisableDeskphoneApiMethodOPTIONS:
    Type: AWS::ApiGateway::Method
    DependsOn: DisableDeskphoneApi
    Properties:
      ResourceId: !Ref DisableDeskphoneApiResource
      RestApiId: !Ref DisableDeskphoneApi
      AuthorizationType: NONE
      HttpMethod: OPTIONS
      Integration:
        IntegrationResponses:
          - StatusCode: 200
            ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
              method.response.header.Access-Control-Allow-Origin: "'*'"
            ResponseTemplates:
              application/json: ''
        PassthroughBehavior: WHEN_NO_MATCH
        RequestTemplates:
          application/json: '{"statusCode": 200}'
        Type: MOCK
      MethodResponses:
        - ResponseModels:
            application/json: 'Empty'
          ResponseParameters:
            method.response.header.Access-Control-Allow-Headers: false
            method.response.header.Access-Control-Allow-Methods: false
            method.response.header.Access-Control-Allow-Origin: false
          StatusCode: 200


  DeskphoneDisableGetAgentsMethod:
    Type: AWS::ApiGateway::Method
    DependsOn: DisableDeskphoneApi
    Properties:
      ResourceId: !Ref GetAgentsApiResource
      RestApiId: !Ref DisableDeskphoneApi
      AuthorizationType: NONE
      HttpMethod: GET
      Integration:
        IntegrationHttpMethod: POST
        Credentials: !GetAtt DisableDeskphoneApiRole.Arn
        Type: AWS_PROXY
        Uri:
          Fn::Join:
          - ''
          - - 'arn:aws:apigateway:'
            - Ref: AWS::Region
            - :lambda:path/2015-03-31/functions/
            - Fn::GetAtt:
              - DeskphoneDisableGetAgents
              - Arn
            - /invocations
        IntegrationResponses:
          - StatusCode: 200
            ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Methods: "'GET,OPTIONS'"
              method.response.header.Access-Control-Allow-Origin: "'*'"
            ResponseTemplates:
              application/json: ''
        PassthroughBehavior: WHEN_NO_MATCH
        RequestTemplates:
          application/json: '{"statusCode": 200}'
      MethodResponses:
        - ResponseModels:
            application/json: 'Empty'
          ResponseParameters:
            method.response.header.Access-Control-Allow-Headers: true
            method.response.header.Access-Control-Allow-Methods: true
            method.response.header.Access-Control-Allow-Origin: true
          StatusCode: 200

  DeskphoneDisableGetAgentsMethodOPTIONS:
    Type: AWS::ApiGateway::Method
    DependsOn: DisableDeskphoneApi
    Properties:
      ResourceId: !Ref GetAgentsApiResource
      RestApiId: !Ref DisableDeskphoneApi
      AuthorizationType: NONE
      HttpMethod: OPTIONS
      Integration:
        IntegrationResponses:
          - StatusCode: 200
            ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Methods: "'GET,OPTIONS'"
              method.response.header.Access-Control-Allow-Origin: "'*'"
            ResponseTemplates:
              application/json: ''
        PassthroughBehavior: WHEN_NO_MATCH
        RequestTemplates:
          application/json: '{"statusCode": 200}'
        Type: MOCK
      MethodResponses:
        - ResponseModels:
            application/json: 'Empty'
          ResponseParameters:
            method.response.header.Access-Control-Allow-Headers: false
            method.response.header.Access-Control-Allow-Methods: false
            method.response.header.Access-Control-Allow-Origin: false
          StatusCode: 200


  DeskphoneDisableIsAdminMethod:
    Type: AWS::ApiGateway::Method
    DependsOn: DisableDeskphoneApi
    Properties:
      ResourceId: !Ref IsAdminApiResource
      RestApiId: !Ref DisableDeskphoneApi
      AuthorizationType: NONE
      HttpMethod: POST
      Integration:
        IntegrationHttpMethod: POST
        Credentials: !GetAtt DisableDeskphoneApiRole.Arn
        Type: AWS_PROXY
        Uri:
          Fn::Join:
          - ''
          - - 'arn:aws:apigateway:'
            - Ref: AWS::Region
            - :lambda:path/2015-03-31/functions/
            - Fn::GetAtt:
              - DeskphoneDisableIsAdmin
              - Arn
            - /invocations
        IntegrationResponses:
          - StatusCode: 200
            ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
              method.response.header.Access-Control-Allow-Origin: "'*'"
            ResponseTemplates:
              application/json: ''
        PassthroughBehavior: WHEN_NO_MATCH
        RequestTemplates:
          application/json: '{"statusCode": 200}'
      MethodResponses:
        - ResponseModels:
            application/json: 'Empty'
          ResponseParameters:
            method.response.header.Access-Control-Allow-Headers: true
            method.response.header.Access-Control-Allow-Methods: true
            method.response.header.Access-Control-Allow-Origin: true
          StatusCode: 200

  DeskphoneDisableIsAdminMethodOPTIONS:
    Type: AWS::ApiGateway::Method
    DependsOn: DisableDeskphoneApi
    Properties:
      ResourceId: !Ref IsAdminApiResource
      RestApiId: !Ref DisableDeskphoneApi
      AuthorizationType: NONE
      HttpMethod: OPTIONS
      Integration:
        IntegrationResponses:
          - StatusCode: 200
            ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
              method.response.header.Access-Control-Allow-Origin: "'*'"
            ResponseTemplates:
              application/json: ''
        PassthroughBehavior: WHEN_NO_MATCH
        RequestTemplates:
          application/json: '{"statusCode": 200}'
        Type: MOCK
      MethodResponses:
        - ResponseModels:
            application/json: 'Empty'
          ResponseParameters:
            method.response.header.Access-Control-Allow-Headers: false
            method.response.header.Access-Control-Allow-Methods: false
            method.response.header.Access-Control-Allow-Origin: false
          StatusCode: 200


  DisableDeskphoneApiModel:
    Type: AWS::ApiGateway::Model
    Properties:
      ContentType: 'application/json'
      RestApiId: !Ref DisableDeskphoneApi
      Schema: {}

  DisableDeskphoneStage:
    DependsOn: DisableDeskphoneApi
    Properties:
      DeploymentId: !Ref DisableDeskphoneApiDeployment
      MethodSettings:
      - DataTraceEnabled: true
        HttpMethod: '*'
        LoggingLevel: INFO
        ResourcePath: /*
      RestApiId: !Ref DisableDeskphoneApi
      StageName: Prod
    Type: AWS::ApiGateway::Stage

  ScheduledRule:
    Type: AWS::Events::Rule
    Properties:
      Description: "ScheduledRule"
      ScheduleExpression: "cron(/5 * ? * MON-FRI *)"
      State: "ENABLED"
      Targets:
        -
          Arn:
            Fn::GetAtt:
              - "DeskphoneDisableGetAgentInfo"
              - "Arn"
          Id: "DeskphoneDisableGetAgentInfo"
  PermissionForEventsToInvokeLambda:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !Ref "DeskphoneDisableGetAgentInfo"
      Action: "lambda:InvokeFunction"
      Principal: "events.amazonaws.com"
      SourceArn:
        Fn::GetAtt:
          - "ScheduledRule"
          - "Arn"

  LambdaApiGatewayInvokeForIsAdmin:
    Type: "AWS::Lambda::Permission"
    DependsOn: DeskphoneDisableIsAdminMethod
    Properties:
      Action: "lambda:InvokeFunction"
      FunctionName: !GetAtt "DeskphoneDisableIsAdmin.Arn"
      Principal: "apigateway.amazonaws.com"
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${DisableDeskphoneApi}/*/POST/DeskphoneDisable-IsAdmin"

  LambdaApiGatewayInvokeForDisableDeskphone:
    Type: "AWS::Lambda::Permission"
    DependsOn: DisableDeskphoneApiMethod
    Properties:
      Action: "lambda:InvokeFunction"
      FunctionName: !GetAtt "DeskphoneDisableDeskPhone.Arn"
      Principal: "apigateway.amazonaws.com"
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${DisableDeskphoneApi}/*/POST/DeskphoneDisable-DisableDeskPhone"

  LambdaApiGatewayInvokeForGetAgents:
    Type: "AWS::Lambda::Permission"
    DependsOn: DeskphoneDisableGetAgentsMethod
    Properties:
      Action: "lambda:InvokeFunction"
      FunctionName: !GetAtt "DeskphoneDisableGetAgents.Arn"
      Principal: "apigateway.amazonaws.com"
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${DisableDeskphoneApi}/*/GET/DeskphoneDisable-GetAgents"
